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
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With