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

This prints:

driving

Instance Variable and Instance Method

Rhonda Asks

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.

p car.instance_variables

This prints:

[:@color]

Instance Variables Live in 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.

p Car.instance_variables

This prints:

[]

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.

p Car.instance_methods(false)

This prints:

[:drive]

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.

Drive Instance Method The illustration shows that you can define many instance methods in the Car class. If you print the instance methods for the car object:

p car.instance_methods(false)

You will get an error:

NoMethodError: undefined method ‘instance_methods’ for #<Car:0x00ca0 @color="red">

Key Takeaways

  • Instance methods live in the class.
  • Instance variables live in the object.
  • Instance variables are unique to each object.

Summary

In this chapter, you learned about the state and behavior and where the instance methods and instance variables live.

results matching ""

    No results matching ""