So I have a for loop thats creating a hash or array depending on whats being passed in.
I need to create these arrays and Hashes with names based on whats being passed in.
Its much the same as
window['MyNewArray-' + i] = [];
In javascript. Is there any equivalent for Ruby?
So I have a for loop thats creating a hash or array depending on whats being passed in.
I need to create these arrays and Hashes with names based on whats being passed in.
Its much the same as
window['MyNewArray-' + i] = [];
In javascript. Is there any equivalent for Ruby?
Share Improve this question asked Aug 15, 2011 at 11:39 OVERTONEOVERTONE 12.2k20 gold badges74 silver badges87 bronze badges 2- 2 If you have to create variables with dynamic names your code is most likely broken. Consider putting the elements into an array/dict-like container. – ThiefMaster Commented Aug 15, 2011 at 11:43
- Its because I have nested arrays and would like to bring them up a level. So rather than saying container[0][0] Id like to have a bunch of top level arrays to access. In fact its kind of a necessity. It wouldn't be a mon thing that I would do. – OVERTONE Commented Aug 15, 2011 at 12:31
4 Answers
Reset to default 4You could do something like:
window = {}
5.times do |i|
window["my_new_array_#{i}"]=[]
end
That same code does work in Ruby, too, and does the same thing.
Well you can create a Ruby hash using :
h = {}
and then add a key/value pair using the store
or the []=
operator.
Like this :
h["foo_#{i}"] = []
Documentation
window = Hash[1.upto(5).map { |n| ["name-#{i}", []] }]