0

I have a few similarly named arrays and I need to loop through the array names:

level_1_foo
level_2_foo
level_3_foo
level_4_foo
level_5_foo

I'd like to do something like the following where x is the value of the digit in the array name:

(1..5).each do |x|
  level_x_foo << some-value
end

Can this be done? I've tried "level_#{x}_foo", level_+x+_foo, and a couple others, to no success.

Thanks

1
  • 7
    Instead of multiple local variables, a common approach is to use an Array or Hash instead where you can use the level as an index as appropriate, e.g. data = {1 => some_value, 2 => some_other_value} You can then easily access the data with data[1]. Having to "dynamically" access a variable is generally an anti-pattern and should be replaced with actual data structures (which is also much faster usually). Commented Dec 11, 2023 at 21:11

2 Answers 2

2

You could do something like this

# Initialize a hash
levels = {}

# Initialize your arrays
(1..5).each do |x|
   levels["level_#{x}_foo"] = []
end

# Now you can access your arrays like this
(1..5).each do |x|
  levels["level_#{x}_foo"] << 'some-value'
end
Sign up to request clarification or add additional context in comments.

Comments

0

One way to do it is to retrieve the arrays with binding.local_variable_get:

(1..5).each do |x|
  binding.local_variable_get("level_#{x}_foo") << some-value
end

You could also do it with eval, but the above approach minimizes the code that is dynamically evaluated.

1 Comment

Thank you! I came across eval after I posted my question. I also read it was sketchy to use it. I had not seen the binding.local_variable_get() before. And now I know.

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.