Ruby Variable Interpolation in Array Names

106 views Asked by At

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

2

There are 2 answers

1
Dave Schweisguth On BEST ANSWER

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.

0
Rajagopalan On

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