rubystring-interpolationruby-3.1

Ruby Variable Interpolation in Array Names


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


Solution

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