在Ruby中动态设置局部变量 [英] Dynamically set local variables in Ruby
问题描述
我对在Ruby中动态设置局部变量感兴趣.不创建方法,常量或实例变量.
I'm interested in dynamically setting local variables in Ruby. Not creating methods, constants, or instance variables.
所以像这样:
args[:a] = 1
args.each_pair do |k,v|
Object.make_instance_var k,v
end
puts a
> 1
我想要局部变量,特别是因为所讨论的方法存在于模型中,并且我不想污染全局空间或对象空间.
I want locally variables specifically because the method in question lives in a model and I dont want to pollute the global or object space.
推荐答案
此处的问题是each_pair中的块具有不同的作用域.在其中分配的任何局部变量将只能在其中访问.例如,这:
The problem here is that the block inside each_pair has a different scope. Any local variables assigned therein will only be accessible therein. For instance, this:
args = {}
args[:a] = 1
args[:b] = 2
args.each_pair do |k,v|
key = k.to_s
eval('key = v')
eval('puts key')
end
puts a
产生此:
1
2
undefined local variable or method `a' for main:Object (NameError)
为了解决这个问题,您可以创建一个本地哈希,为该哈希分配密钥,然后在其中访问它们,就像这样:
In order to get around this, you could create a local hash, assign keys to this hash, and access them there, like so:
args = {}
args[:a] = 1
args[:b] = 2
localHash = {}
args.each_pair do |k,v|
key = k.to_s
localHash[key] = v
end
puts localHash['a']
puts localHash['b']
当然,在此示例中,它只是复制带有键字符串的原始哈希.我假设实际用例更加复杂.
Of course, in this example, it's merely copying the original hash with strings for keys. I'm assuming that the actual use-case, though, is more complex.
这篇关于在Ruby中动态设置局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!