2010-02-21 114 views
5

如何让代码在下方工作,以便puts显示1如何在Ruby中使用变量作为变量名?

video = [] 
name = "video" 

name[0] = 1 

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

如果你真的必须使用'eval()'。请参阅http://stackoverflow.com/questions/2168666/is-it-possible-to-do-dynamic-variables-in-ruby的回答 – molf 2010-02-21 22:35:00

回答

7

你可以把它的工作使用eval:

eval "#{name}[0] = 1" 

我强烈反对,虽然。在大多数情况下,如果你认为你需要这样做,你应该使用hashmap。像:

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

@ sepp2k:你为什么强烈反对使用eval? – Radek 2010-02-21 23:31:28

+3

@Radek:3000年的经验,如腮腺炎破碎的系统;这是一种经典的代码气味,它会让你的代码难以理解和维护。 – 2010-02-21 23:43:19

+3

@Radek:首先,如果您评估用户输入,这是一个主要的安全漏洞。对于另一个hashmaps更适合从变量名称映射到值。另一方面,使用eval的代码可能是一个很难调试的问题。 – sepp2k 2010-02-21 23:48:08

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