javascript - Dynamically naming ArraysHashes in Ruby - Stack Overflow

So I have a for loop thats creating a hash or array depending on whats being passed in.I need to create

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
Add a ment  | 

4 Answers 4

Reset to default 4

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742361516a4429485.html

相关推荐

  • javascript - Dynamically naming ArraysHashes in Ruby - Stack Overflow

    So I have a for loop thats creating a hash or array depending on whats being passed in.I need to create

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信