2010-02-21 52 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

相關問題