method
instance_variable_set
instance_variable_set(p1, p2)
public
Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.
class Fred def initialize(p1, p2) @a, @b = p1, p2 end end fred = Fred.new('cat', 99) fred.instance_variable_set(:@a, 'dog') #=> "dog" fred.instance_variable_set(:@c, 'cat') #=> "cat" fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
Register or
log in
to add new notes.
kyptin -
November 18, 2009 - (>= v1_8_6_287)
5 thanks
Example
code:
class Klass def set(string) var_name = "@#{string}" # the '@' is required self.instance_variable_set(var_name, 'bar') end def puts_foo puts @foo end end k = Klass.new k.puts_foo # nil k.set('foo') k.puts_foo # 'bar'