Ruby Instance Variables

Ruby instance variables are bound to self, an object that changes based on the program’s context. Instance variables are usually bound to instances of a class, but they can also be bound to class objects.

class Thailand
  def weather
    @temp = 'hot!'
  end
end

obj = Thailand.new
obj.instance_variables # => []
# call the weather() method to bind @temp to obj
obj.weather()
obj.instance_variables # => [:@temp]

Instance variables are often bound to class instances in the initialize method, which is called right when the object is created.

class Bird
  def initialize
    @sound = 'chirp chirp'
  end
end

b = Bird.new
b.instance_variables # => [:@sound]

Instance variables are bound to self, even when self points to a class object. Previous examples demonstrate how to bind instance variables to a class instance and the next example shows how to bind instance variables to a class object.

class Snake
  p self # => Snake
  # @noise is bound to the Snake object
  @noise = 'hisssss'

  def self.about
    p self # => Snake
    # @movement is bound to the Snake object
    @movement = 'slither'
  end
end

Snake.instance_variables # => [:@noise]
Snake.about
Snake.instance_variables # => [:@noise, :@movement]

Instance variables bound to the class object are referred to as class instance variables.

The instance variables for an object can also be set and retrieved with instance_variable_get and instance_variable_set.

obj = Object.new
obj.instance_variable_set(:@bugs, 'want blood')
obj.instance_variables # => [:@bugs]
obj.instance_variable_get(:@bugs) # => 'want blood'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s