Adding an instance variable to a class in Ruby

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\">

Leave a Comment