OVERTONE
OVERTONE

Reputation: 12207

Dynamically naming Arrays/Hashes in 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?

Upvotes: 2

Views: 2672

Answers (4)

tokland
tokland

Reputation: 67900

window = Hash[1.upto(5).map { |n| ["name-#{i}", []] }]

Upvotes: 1

Rahman Kalfane
Rahman Kalfane

Reputation: 1717

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

Upvotes: 2

Jörg W Mittag
Jörg W Mittag

Reputation: 369536

That same code does work in Ruby, too, and does the same thing.

Upvotes: 2

lucapette
lucapette

Reputation: 20724

You could do something like:

window = {}
5.times do |i|
  window["my_new_array_#{i}"]=[]
end

Upvotes: 4

Related Questions