开发者

How can I use a variable as a variable name in Ruby?

开发者 https://www.devze.com 2022-12-20 16:58 出处:网络
How can I make the code below work, so that both puts display 1? video = [] name = \"video\" name[0] =开发者_C百科 1

How can I make the code below work, so that both puts display 1?

video = []
name = "video"

name[0] =开发者_C百科 1

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


You can make it work using eval:

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

I strongly advise against that though. In most situations where you think you need to do something like that, you should probaby use a hashmap. Like:

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


Here the eval function.

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)

Here is the eval() doc.


Before you look at the eval suggestions, please, please, please read these:

  • http://perl.plover.com/varvarname.html
  • http://perl.plover.com/varvarname2.html
  • http://perl.plover.com/varvarname3.html

(Yes, those are about Perl in their specifics. The larger point holds regardless of the language, I think.)

0

精彩评论

暂无评论...
验证码 换一张
取 消