Ruby-使用字符串作为变量名称来定义新变量

Sha*_*nde 0 ruby arrays string metaprogramming ruby-on-rails

我有一个字符串数组:

names = ['log_index', 'new_index']
Run Code Online (Sandbox Code Playgroud)

我要做的是从名称创建变量:

names.each { |name| name = [] } # obviously it does not do what I want
Run Code Online (Sandbox Code Playgroud)

这些变量不会在代码中的任何位置之前声明。

我该怎么办?

Dan*_*sky 6

没有办法在Ruby中动态定义新的局部变量

尽管使用Ruby在Ruby 1.8中是可能的eval 'x = 2'

您可以使用eval或更改现有变量binding.local_variable_set

我会考虑使用hash存储值。