0

给出以下代码:

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 进行变异?

4

2 回答 2

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
于 2012-10-19T21:33:06.833 回答
1

同意 pje,您可能应该在 irb 中对此进行测试,但我假设您想为每个实例变量捕获一个 setter,所以我建议您这样做:

setters = instance_variables.map{|v| lambda { |val| instance_variable_set(v, val) }}

那么你可以这样做setters[0].call(__VALUE__),它会相应地设置值。

你想达到什么目的?

于 2012-10-19T21:40:00.317 回答