Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a variable as a variable name in Ruby?

Tags:

variables

ruby

How can I make the code below work, so that both puts display 1?

video = []
name = "video"

name[0] = 1

puts name[0] #gives me 1
puts video[0] #gives me nil
like image 927
Radek Avatar asked Feb 21 '10 22:02

Radek


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.

Can you use a in a variable name?

The first character must be a letter or an underscore (_). You can't use a number as the first character. The rest of the variable name can include any letter, any number, or the underscore. You can't use any other characters, including spaces, symbols, and punctuation marks.

What is '@' in Ruby?

The @ symbol before a variable tells Ruby that we are working with an instance variable, and @@ before a variable tells us we are working with a class variable. We use @ before a variable in instance methods within a class to tell Ruby to access that attribute (instance variable) of the instance.


2 Answers

You can make it work using eval:

eval "#{name}[0] = 1"

I strongly advise against that though. In most situations where you think you need to do something like that, you should probaby use a hashmap. Like:

context = { "video" => [] }
name = "video"
context[name][0] = 1
like image 105
sepp2k Avatar answered Oct 29 '22 01:10

sepp2k


Here the eval function.

video = [] #there is now a video called array
name = "video" #there is now a string called name that evaluates to "video" 
puts eval(name) #prints the empty array video
name[0] = 1 #changes the first char to value 1 (only in 1.8.7, not valid in 1.9.1)

Here is the eval() doc.

like image 44
lillq Avatar answered Oct 29 '22 02:10

lillq