Ruby Basics : State and Behavior
Instance variables represent the state of an object. The instance methods defined in the class provide the behavior for an object. Every object has its own unique state. But they share the same instance method behavior defined in the class. We can have a black car that has its own color that shares the drive method.
class Car def initialize(color) @color = color end def drive 'driving' end end black_car = Car.new('black') p black_car.drive
Why is the method defined in the Car class called as an instance method?
Because, we need an instance of the Car class to call the method.
Instance Variables Live in the Object
We can ask Ruby to list all the instance variables for car object.
The illustration shows that you can define many instance variables such as color, model of the car etc. for a car. Let's print the instance variables in the Car class.
The result array is empty. There are no instance variables in the Car class.
Instance Method Lives in the Class
We can ask Ruby for the list of instance methods in the Car class.
The Car class defines the drive instance method, so it shows up in the output. We pass false to the
instance_methods to print instance methods found in the Car class only.
The illustration shows that you can define many instance methods in the Car class. If you print the instance methods for the car object:
You will get an error:
NoMethodError: undefined method ‘instance_methods’ for #<Car:0x00ca0 @color="red">
- Instance methods live in the class.
- Instance variables live in the object.
- Instance variables are unique to each object.
In this article, you learned about the state and behavior and where the instance methods and instance variables live.