开发者

Dynamically naming Arrays/Hashes in Ruby

开发者 https://www.devze.com 2023-03-28 08:03 出处:网络
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.

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

精彩评论

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

关注公众号