如何在Ruby中使用变量作为变量名?
问题描述:
如何让代码在下方工作,以便puts
显示1
?如何在Ruby中使用变量作为变量名?
video = []
name = "video"
name[0] = 1
puts name[0] #gives me 1
puts video[0] #gives me nil
答
你可以把它的工作使用eval:
eval "#{name}[0] = 1"
我强烈反对,虽然。在大多数情况下,如果你认为你需要这样做,你应该使用hashmap。像:
context = { "video" => [] }
name = "video"
context[name][0] = 1
答
这里的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。
答
你看看eval
建议之前,请,请,请阅读这些:
- http://perl.plover.com/varvarname.html
- http://perl.plover.com/varvarname2.html
- http://perl.plover.com/varvarname3.html
(是的,这些都是有关Perl在自己我认为,不管语言如何,更大的一点是成立的。)
如果你真的必须使用'eval()'。请参阅http://*.com/questions/2168666/is-it-possible-to-do-dynamic-variables-in-ruby的回答 – molf 2010-02-21 22:35:00