如何讓代碼在下方工作,以便puts
顯示1
?如何在Ruby中使用變量作爲變量名?
video = []
name = "video"
name[0] = 1
puts name[0] #gives me 1
puts video[0] #gives me nil
如何讓代碼在下方工作,以便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
建議之前,請,請,請閱讀這些:
(是的,這些都是有關Perl在自己我認爲,不管語言如何,更大的一點是成立的。)
如果你真的必須使用'eval()'。請參閱http://stackoverflow.com/questions/2168666/is-it-possible-to-do-dynamic-variables-in-ruby的回答 – molf 2010-02-21 22:35:00