在Ruby中,没有办法在当前上下文中动态定义局部变量吗? [英] In Ruby, is there no way to dynamically define a local variable in the current context?
问题描述
我想知道是否有一种方法可以让我在当前上下文中动态定义以前未定义的变量.例如:
I'm wondering if there is a method which will allow me to dynamically define a previously undefined variable in the current context. For example:
foo # => NameError: undefined method or local variable ...
# Some method call which sets foo = 1 in the local context
foo # => 1
换一种说法,鉴于foo
是未定义的,我正在寻找可以让我定义局部变量foo
而不使用foo
变量的任何代码(例如,如果我有一些其他变量:foo
,我不得不依靠它来设置foo
的值.)
Put another way, given that foo
is undefined, I'm looking for any code that would let me define the local variable foo
without using the foo
variable (e.g. if I had some other variable bar
whose value was :foo
and I had to rely on that to set the value of foo
).
eval('foo = 1')
或eval('foo = 1', binding)
或在Ruby 2.1中binding.local_variable_set(:foo, 1)
似乎都等同于:
It seems that eval('foo = 1')
or eval('foo = 1', binding)
or, in Ruby 2.1, binding.local_variable_set(:foo, 1)
are all equivalent to:
1.times do
foo = 1
end
换句话说,它们在 new 本地上下文的上下文中设置foo
,以便在该上下文之外无法访问该值.
in other words, they set foo
in the context of a new local context, such that the value is inaccessible outside of that context.
我想做的是可能的吗?
更新:此问题并非特定于任何特定的局部变量上下文(模块/类,方法,proc,块等).我有兴趣明确地知道可以或不能做到的任何情况.
Update: This question is not specific to any particular local variable context (module/class, method, proc, block, etc.). I'd be interested in knowing definitively any context where it can or cannot be done.
推荐答案
似乎Ruby的魔力会提供一种方法,但是根据Matz的说法,这仅在1.8中通过eval
且仅在某些情况下才有可能(即irb
).从1.9开始,此行为已被删除(严格禁止"):
It seems that Ruby's magic would provide a way, but according to Matz, this was only possible in 1.8 via eval
and only in certain contexts (i.e. irb
). As of 1.9, this behavior was taken out ("strictly forbidden"):
Matz亲自参与其中: https://www.ruby-forum.com/topic/155673#685906
Matz himself weighs in here: https://www.ruby-forum.com/topic/155673#685906
我从某个地方读到,现在Ruby无法动态创建局部变量.是真的还是错误?
局部变量是在编译时创建的,因此局部 eval()中定义的变量不能在外部访问 评估.在1.8中,irb和tryruby逐行进行编译,以便 局部变量从eval()中溢出,但是在1.9中,严格来说 即使在逐行编译的情况下也是禁止的.
The local variables are created in compile time, so that local variables that are defined in eval() cannot be accessed outside of eval. In 1.8, irb and tryruby does line by line compilation so that local variables are spilled from eval(), but in 1.9, it's strictly prohibited even under line-by-line compilation.
matz.
(这里是非必填项,对于那些想要这样但又不是发问者确切的技术状况的人):
(Non-sequitur alternative here, for anyone who wants something like this but not the exact technical situation that the questioner has):
使用哈希:
local_hash = {}
my_vars.each_pair do |k,v|
local_hash[k] = v
end
puts local_hash['foo']
#=> 'baz'
这篇关于在Ruby中,没有办法在当前上下文中动态定义局部变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!