如何在Ruby中使用变量作为变量名?

时间:2010-02-21 22:25:41

标签: ruby variables

如何让下面的代码生效,以便puts显示1

video = []
name = "video"

name[0] = 1

puts name[0] #gives me 1
puts video[0] #gives me nil

3 个答案:

答案 0 :(得分:7)

您可以使用eval:

使其工作
eval "#{name}[0] = 1"

我强烈建议不要这样做。在大多数情况下,你认为你需要做类似的事情,你应该使用hashmap。像:

context = { "video" => [] }
name = "video"
context[name][0] = 1

答案 1 :(得分:3)

这里是eval函数。

video = [] #there is now a video called array
name = "video" #there is now a string called name that evaluates to "video" 
puts eval(name) #prints the empty array video
name[0] = 1 #changes the first char to value 1 (only in 1.8.7, not valid in 1.9.1)

这是eval() doc

答案 2 :(得分:2)

在您查看eval建议之前,请阅读以下内容:

(是的,那些是关于Perl的具体细节。我认为无论语言如何,都有更大的观点。)