class Foo
def initialize
@foo = 1
end
end
obj = Foo.new
p obj.instance_variable_get("@foo") # => 1
p obj.instance_variable_get(:@foo) # => 1
p obj.instance_variable_get(:@bar) # => nil
instance_variable_set(var, val)
ruby 1.8 特性
将val的值赋值给对象的实例变量并返回该值.
可以使用字符串或Symbol来向var设定实例变量名.
若实例变量尚未定义,则重新定义.
obj = Object.new
p obj.instance_variable_set("@foo", 1) # => 1
p obj.instance_variable_set(:@foo, 2) # => 2
p obj.instance_variable_get(:@foo) # => 2