user3742048
user3742048

Reputation: 47

Setting elements of an array as variables in Ruby

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

Answers (3)

SteveTurczyn
SteveTurczyn

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

Filip Bartuzi
Filip Bartuzi

Reputation: 5931

If you want to set instance variable you should probably call @var = array[0]

Upvotes: 0

Jordan Samuels
Jordan Samuels

Reputation: 997

Just set it like an array in most languages:

array[0] = var

Upvotes: 3

Related Questions