Reputation: 47
Say I have an array holding some variables such as array = ["one", "two", "three"]
.
How would I assign array[0]
to be a variable? I know this is probably the wrong way of implementing this, but I'm trying something like this:
var = 10
instance_variable_set("@#{array[0]}", var)
I want to be able to call puts @"#{array[0]}"
and it give me 10
as a result.
Edit: I am trying to set the array index (in this case "one") to be a new variable so that I can later call it in other methods. This way set!
works for changing the variable later when the array not longer holds the same values. For example, if after setting "one"
as a new variable whose value is 10
, if i get an array containing ["three", "two", "one"]
I want to be able to call puts array[2]
and it give me 10
.
Upvotes: 1
Views: 1898
Reputation: 36860
eval "@#{array[0]} = var"
p @one
=> 10
or
eval "p @#{array[0]}"
=> 10
as A Fader Darkly points out, eval is potentially dangerous, particularly if the value comes from user input. What if the user enters, as a string, "`rm -rf /`" ? You've now wiped out everything in your root folder.
Upvotes: 0
Reputation: 5931
If you want to set instance variable you should probably call @var = array[0]
Upvotes: 0