Ruby-使用字符串作为变量名称来定义新变量 [英] Ruby -- use a string as a variable name to define a new variable
本文介绍了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
存储值.
这篇关于Ruby-使用字符串作为变量名称来定义新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文