Adding an instance variable to a class in Ruby

Readonly picture Readonly · Sep 30, 2008 · Viewed 39k times · Source

How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?

I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.

Answer

Gordon Wilson picture Gordon Wilson · Sep 30, 2008

Ruby provides methods for this, instance_variable_get and instance_variable_set. (docs)

You can create and assign a new instance variables like this:

>> foo = Object.new
=> #<Object:0x2aaaaaacc400>

>> foo.instance_variable_set(:@bar, "baz")
=> "baz"

>> foo.inspect
=> #<Object:0x2aaaaaacc400 @bar=\"baz\">