Ruby Basics : Object

In this article, you will the learn the basics of an object and how to create them.

Car Class

In the previous article, we defined a Car class. It has drive method that provides the behavior for the Car class.

class Car 
  def drive
    return 'driving'
  end
end

Car Class Analogy

Car class is like a car blueprint.

Car Blueprint

Car Object Analogy

Car object is like a car made using the car blueprint.

Car Object

We cannot drive a car blueprint. We need a real car to exercise the drive behavior. How we do we create a car that we can drive in a Ruby program?

Car Object

We use the blueprint to create an object. The process of creating an object from a class is called instantiation. In Ruby the new method is used for instantiating an object. Let's create an instance of the Car class.

class Car 
  def drive
    return 'driving'
  end
end

car = Car.new

We now have a car object. How do we invoke the drive behavior of the car object?

Sending the Message

We invoke the drive behavior by sending a message to the car object. Let's send the drive message to the car object.

p car.drive

The dot notation is used to send a message to any object. This prints:

driving

From now on, you will hear calling a method and invoking a method. These terms mean the same thing as sending a message.

Return Value of Method

In Ruby, the last statement executed is the return value of a method. We can simplify the program by removing the return statement in the drive method.

class Car 
  def drive
    'driving'
  end
end

car = Car.new('red')
p car.drive

This will still print:

driving

Key Takeaway

  • Every object is an instance of a class.

Summary

In this article, we created a car object by creating an instance of the Car class. We invoked the instance method by sending a drive message.


Related Articles


Create your own user feedback survey