Ruby Basics : Object
In this article, you will the learn the basics of an object and how to create them.
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 Object Analogy
Car object is like a car made using the car blueprint.
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?
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.
The dot notation is used to send a message to any object. This prints:
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:
- Every object is an instance of a class.
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.
Ace the Technical Interview
- Easily find the gaps in your knowledge
- Get customized lessons based on where you are
- Take consistent action everyday
- Builtin accountability to keep you on track
- You will solve bigger problems over time
- Get the job of your dreams
Take the 30 Day Coding Skills Challenge
Gain confidence to attend the interview