如何动态创建局部变量? [英] How to dynamically create a local variable?
问题描述
我有一个变量 var = "some_name"
,我想创建一个新对象并将其分配给 some_name
.我该怎么做?例如
I have a variable var = "some_name"
and I would like to create a new object and assign it to some_name
. How can I do it? E.g.
var = "some_name"
some_name = Struct.new(:name) # I need this
a = some_name.new('blah') # so that I can do this.
推荐答案
您不能在 Ruby 1.9+ 中动态创建局部变量(您可以在 Ruby 1.8 中通过 eval
):
You cannot dynamically create local variables in Ruby 1.9+ (you could in Ruby 1.8 via eval
):
eval 'foo = "bar"'
foo # NameError: undefined local variable or method `foo' for main:Object
不过,它们可以在 eval-ed 代码本身中使用:
They can be used within the eval-ed code itself, though:
eval 'foo = "bar"; foo + "baz"'
#=> "barbaz"
Ruby 2.1 添加了 local_variable_set
,但这不能创建新的局部变量:
Ruby 2.1 added local_variable_set
, but that cannot create new local variables either:
binding.local_variable_set :foo, 'bar'
foo # NameError: undefined local variable or method `foo' for main:Object
这种行为不能在不修改 Ruby 本身的情况下被改变.另一种方法是考虑将您的数据存储在另一个数据结构中,例如一个哈希,而不是许多局部变量:
This behavior cannot be changed without modifying Ruby itself. The alternative is to instead consider storing your data within another data structure, e.g. a Hash, instead of many local variables:
hash = {}
hash[:my_var] = :foo
<小时>
请注意,eval
和 local_variable_set
do 都允许重新分配现有的局部变量:
Note that both eval
and local_variable_set
do allow reassigning an existing local variable:
foo = nil
eval 'foo = "bar"'
foo #=> "bar"
binding.local_variable_set :foo, 'baz'
foo #=> "baz"
这篇关于如何动态创建局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!