Is it possible to create multiple variables by iterating over an array?
For example, say I had an array called numbers = [1,2,3,4,5] and I wanted to create a series of variables called number_1, number_2,...,number_5 each equal to their respective index in the numbers array (e.g. number_1 = 1, number_2 = 2, etc.).
I tried something along the lines of the following:
numbers.each_with_index do |num, index|
number_"#{index+1}" = num
end
But that failed.
Essentially, I would like for the iterating process to automate creating and assigning values to variables.
Thank you.
One way is:
instance_variable_set("@number_#{index+1}", num)
Another way is using the eval method to create an instance variable:
eval "@number_#{index+1} = #{num}"
Heads up that eval is considered a bit hacky, and doesn't work on JRuby.
(Caveat: the code above creates instance variables, not scope-level variables (a.k.a. local variables). Example: the code creates @number_1 not number_1. As far as I'm aware Ruby does not offer a straightforward way to dynamically create a scope-level variable that persists; you can create one within an eval but it goes out of scope beyond the eval.)
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