Ruby Language View an object's Instance Variables


It is possible to query an object about its instance variables using instance_variables, instance_variable_defined?, and instance_variable_get, and modify them using instance_variable_set and remove_instance_variable:

class Foo
  attr_reader :bar
  def initialize
    @bar = 42
f =
f.instance_variables                #=> [:@bar]
f.instance_variable_defined?(:@baz) #=> false
f.instance_variable_defined?(:@bar) #=> true
f.instance_variable_get(:@bar)      #=> 42
f.instance_variable_set(:@bar, 17)   #=> 17                               #=> 17
f.remove_instance_variable(:@bar)   #=> 17                               #=> nil
f.instance_variables                #=> []

The names of instance variables include the @ symbol. You will get an error if you omit it:

#=> NameError: `jim' is not allowed as an instance variable name