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
end
end
f = Foo.new
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
f.bar #=> 17
f.remove_instance_variable(:@bar) #=> 17
f.bar #=> nil
f.instance_variables #=> []
The names of instance variables include the @
symbol. You will get an error if you omit it:
f.instance_variable_defined?(:jim)
#=> NameError: `jim' is not allowed as an instance variable name