Using the value of a variable as another variables name in Ruby Using the value of a variable as another variables name in Ruby ruby ruby

Using the value of a variable as another variables name in Ruby


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' variablevarname = "myvar"@uservars[varname] = 5   # Set a variable by namevalue = @uservars[varname]  # Get a variable by name 


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".