Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 746
hrickards Avatar asked Mar 27 '10 17:03

hrickards


People also ask

How do you name a variable in Ruby?

Variable names in Ruby can be created from alphanumeric characters and the underscore _ character. A variable cannot begin with a number. This makes it easier for the interpreter to distinguish a literal number from a variable. Variable names cannot begin with a capital letter.

How do you use a global variable in Ruby?

Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($).

How do you use local variables in Ruby?

A local variable is only accessible within the block of its initialization. Local variables are not available outside the method. There is no need to initialize the local variables. Instance Variables: An instance variable name always starts with a @ sign.

How do you add a variable to a string in Ruby?

Instead of terminating the string and using the + operator, you enclose the variable with the #{} syntax. This syntax tells Ruby to evaluate the expression and inject it into the string.


1 Answers

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  
like image 87
rjh Avatar answered Oct 17 '22 07:10

rjh