最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically naming ArraysHashes in Ruby - Stack Overflow

programmeradmin1浏览0评论

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}", []] }]
发布评论

评论列表(0)

  1. 暂无评论