method
instance_variable_set
![Moderate documentation Importance_2](https://d2vfyqvduarcvs.cloudfront.net/images/importance_2.png?1349367920)
instance_variable_set(p1, p2)
public
Sets the instance variable named by symbol to the given object, thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation. The variable does not have to exist prior to this call. If the instance variable name is passed as a string, that string is converted to a symbol.
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)
![Default_avatar_30](https://www.gravatar.com/avatar/6e25e66f3fa7f1631bbdfc79865928bd?size=30&default=http://apidock.com/images/default_avatar_30.png)
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'