ruby - 如何动态创建局部变量?

标签 ruby

我有一个变量 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.1 local_variable_set ,但也不能创建新的局部变量:

binding.local_variable_set :foo, 'bar'
foo # NameError: undefined local variable or method `foo' for main:Object

如果不修改 Ruby 本身,这种行为不能改变。另一种方法是考虑将数据存储在另一个数据结构中,例如一个哈希,而不是许多局部变量:

hash = {}
hash[:my_var] = :foo

请注意,evallocal_variable_set do 都允许重新分配现有局部变量:

foo = nil
eval 'foo = "bar"'
foo  #=> "bar"
binding.local_variable_set :foo, 'baz'
foo  #=> "baz"

关于ruby - 如何动态创建局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552891/

相关文章:

ruby - Hanami 中的 2 个现场验证 + 干式验证

ruby - 更改字符串的特定索引,必要时进行填充

ruby-on-rails - Rails3 和 readline 问题

ruby-on-rails - Rails bundler : how to undo bundle package?

arrays - Ruby:字符串在数组中显示为字符串

ruby - 网络驱动程序。按坐标单击 Canvas 元素

ruby - 在结构体数组中查找 N 个公共(public)属性

ruby - 无法在 pry 中使用 `gem-install` 命令

巨大字符串上的 Ruby 字符串操作

ruby - 无法理解如何索引数组项