Ruby instance_variables Method Tutorial

In this section we will learn what the instance_variable is and how to use it in Ruby.

What is instance_variables Method in Ruby?

The Ruby `instance_variables` as its name suggests, is a method that we can call on top of any object in order to get the list of instance variables it has.

Example: using instance_variables method in Ruby

class Person 
    attr_accessor :first_name, :last_name 

    def initialize (first_name, last_name)
        self.first_name = first_name
        self.last_name = last_name
    end 
end 

puts Person.new("John","Doe").instance_variables

Output:

@first_name

@last_name

In this example, the object we’ve created from the Person class has two instance variables and using the `instance_variables` method, we could print their names to the output stream.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies