给出以下代码:
vars = instance_variables.map(&method(:instance_variable_get))
vars.each {|v| v = 123}
会设置@something = 123吗?
更进一步
如果我有
,它是一样的vars = instance_variables.map(&method(:instance_variable_get))
vars.each {|v| doSomething(v) }
def doSomething(var)
var = 123
end
我如何在函数内变异var?
答案 0 :(得分:1)
您可以很快在irb
中对此进行测试:
@something = 456
instance_variables
# => [:@something]
instance_variables.map(&method(:instance_variable_get)).each { |v| v = 123 }
@something
# => 456 (i.e. "didn't mutate @something")
def doSomething(var)
var = 123
end
vars = instance_variables.map(&method(:instance_variable_get))
vars.each { |v| doSomething(v) }
@something
# => 456 (i.e. "didn't mutate @something")
Object#instance_variable_set但是,确实更改@something
的值:
@something = 456
instance_variables.each { |v| instance_variable_set(v, 123) }
@something
# => 123
答案 1 :(得分:1)
同意pje,您可能应该在irb中对此进行测试,但我假设您想为每个实例变量捕获一个setter,所以我建议使用以下内容:
setters = instance_variables.map{|v| lambda { |val| instance_variable_set(v, val) }}
然后你可以setters[0].call(__VALUE__)
,它会相应地设置值。
你想要实现的目标是什么?