21

I'm just starting out in learning Ruby and I've written a program that generates some numbers and assigns them to variables @one, @two, @three etc. The user can then specify a variable to change by inputting it's name (e.g one). I then need to do something like '@[valueofinout] = asd'. How would I do this, and is there a better way as the way I'm thinking of seems to be discouraged? I've found

x = "myvar"
myvar = "hi"
eval(x) -> "hi"

but I don't completely understand why the second line is needed. In my case would I use something like

@one = "21"
input = "one"
input = "@" + input
changeto = "22"
eval(input) -> changeto
jrg
  • 731
  • 1
  • 17
  • 34
hrickards
  • 1,061
  • 2
  • 9
  • 20

2 Answers2

34

Use instance_variable_set (rubydoc)

instance_variable_set("@" + varname, value)

In most cases though, you should separate your normal Ruby variables from the variables your user is interacting with. How about creating a Hash of user variables, e.g.

@uservars = { 'one' => 1, 'two' => 2 }
two = @uservars['two']   # Look up 'two' variable

varname = "myvar"
@uservars[varname] = 5   # Set a variable by name
value = @uservars[varname]  # Get a variable by name 
rjh
  • 49,276
  • 4
  • 56
  • 63
  • 1
    wow, this is actually one area where PHP outshines ruby in terms of cleanliness of syntax. http://stackoverflow.com/a/4169891/2951835 – ahnbizcad May 09 '15 at 07:06
  • Ruby makes it hard to do because it's ugly, you're rarely need to set a user specified variable of an instance unless you are metaprogramming. Dynamically messing with global variables is a security hole; if you want a set of user-defined variables then you probably want a hash. – rjh Nov 16 '16 at 17:30
2

Instance variables can be retrieved via this method:

input = instance_variable_get("@one")

After this, in your case you'll have input equal to "21".

alex.zherdev
  • 23,914
  • 8
  • 62
  • 56
  • Hi, I'm not quite whether that would work for what I need. I'd need to have something that would assign a certain number to a variable (say variable A) but the name of variable A is not known. The name of variable A is stored within variable B though so I'd need to use the value of variable B to assign something to variable A. AFAICT this can't be done with instance_variable_get. – hrickards Mar 27 '10 at 17:16
  • @hrickards: Do you know the possibles values of A ? if you do there is an other way. But the intance_variable_get should do what you want ! – Nicolas Guillaume Mar 27 '10 at 17:20
  • @Niklaos An integer between and including 1 and 49 – hrickards Mar 27 '10 at 17:23
  • There are only six possible names for variable A, so it would be possible to use if else statements to check for all of them, but I thought there'd be a cleaner way. Is there not? – hrickards Mar 27 '10 at 17:28