3

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.

3
  • 1
    Why do you want to do this? What does number_1 give you that numbers[0] doesn't? Commented Jan 16, 2015 at 22:08
  • This will probably meet your needs: stackoverflow.com/q/16419767/2177 Commented Jan 16, 2015 at 22:11
  • What's the use case for this? Commented Jan 17, 2015 at 0:19

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this will not create local variables (as seems to have been requested). There is no way to create local variables in this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.