开发者

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 wit开发者_JS百科h names based on whats being passed in.

Its much the same as

window['MyNewArray-' + i] = [];

In javascript. Is there any equivalent for Ruby?


You 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}", []] }]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜