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

  def drive

black_car ='black')

This prints:


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:


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:


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.


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

Related Articles

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

No spam ever. Unsubscribe anytime.