Ruby-使用字符串作为变量名称来定义新变量
问题描述:
我有一个字符串数组:
names = ['log_index', 'new_index']
我要做的是从名称中创建变量:
What I want to do is to create variables from the names:
names.each { |name| name = [] } # obviously it does not do what I want
这些变量未在代码中的任何位置之前声明.
Those variables are not declared before anywhere in the code.
我该怎么办?
答
无法在Ruby中动态定义新的局部变量.
There is no way to define new local variables dynamically in Ruby.
尽管使用eval 'x = 2'
,在Ruby 1.8中还是有可能的.
It was possible in Ruby 1.8 though with eval 'x = 2'
.
您可以使用eval
或binding.local_variable_set
更改现有变量.
You can change an existing variable with eval
or binding.local_variable_set
.
我会考虑使用hash
存储值.