What's an Instance Variable in Ruby?

Find out what an instance variable is in Ruby

In Ruby, an instance variable is a variable declared inside a class that's specific to each instantiated object of the class it's defined in (i.e. each class instance has a separate copy of an instance variable). It is:

Consider, for example, the following Person class that has two instance variables; "@name" and "@age":

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
end

To get/set these instance variables from outside the class, you must create getter/setter methods. For example, you can use the attr_reader accessor method to auto-generate getters for the instance variables, like so:

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  attr_reader :name, :age
end

person1 = Person.new("bob", 34)
puts person1.name #=> "bob"
puts person1.age #=> 34

person2 = Person.new("john", 22)
puts person2.name #=> "john"
puts person2.age #=> 22

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.