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 (eg 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 (aka 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
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.