我有一个变量var = "some_name"
我想创建一个新对象并将其分配给some_name
。我该怎么做?例如。
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):
eval 'foo = "bar"'
foo # NameError: undefined local variable or method `foo' for main:Object
不过,它们可以在评估代码本身中使用:
eval 'foo = "bar"; foo + "baz"'
#=> "barbaz"
添加了 Ruby 2.1local_variable_set,但是也不能创建新的局部变量:
binding.local_variable_set :foo, 'bar'
foo # NameError: undefined local variable or method `foo' for main:Object
这种行为cannot无需修改 Ruby 本身即可进行更改。另一种方法是考虑将数据存储在另一个数据结构中,例如一个哈希,而不是许多局部变量:
hash = {}
hash[:my_var] = :foo
请注意,两者eval
and local_variable_set
do允许重新分配现有的局部变量:
foo = nil
eval 'foo = "bar"'
foo #=> "bar"
binding.local_variable_set :foo, 'baz'
foo #=> "baz"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)