5

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

video = []
name = "video"

name[0] = 1

puts name[0] #gives me 1
puts video[0] #gives me nil
Telemachus
  • 19,459
  • 7
  • 57
  • 79
Radek
  • 13,813
  • 52
  • 161
  • 255
  • If you really have to, use `eval()`. See the answer to http://stackoverflow.com/questions/2168666/is-it-possible-to-do-dynamic-variables-in-ruby – molf Feb 21 '10 at 22:35

3 Answers3

7

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
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • @sepp2k: why are you strongly against using eval? – Radek Feb 21 '10 at 23:31
  • 3
    @Radek: 3000 years of experience with broken systems like Mumps; this is a classic code smell, and it will make your code hard to understand and maintain. – Brent.Longborough Feb 21 '10 at 23:43
  • 3
    @Radek: For one thing, it's a major security hole if you eval user input. For another hashmaps are simply more suited to mapping from variable names to values. For yet another, code that uses eval can be a pain to debug. – sepp2k Feb 21 '10 at 23:48
3

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.

lillq
  • 14,758
  • 20
  • 53
  • 58
2

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

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

Telemachus
  • 19,459
  • 7
  • 57
  • 79