如何创建这个multidemsional数组,散列组合?(How do I create this

2019-09-29 07:19发布

我有这个数据 ,我需要这样类型的输出的输出。我基本上需要具备所有的场馆和他们的日期和相关的给他们的所有歌曲....如果有人能想到更好的结构,以及如何实现但我会非常感激......

{ 
["Vector Arena - Auckland Central, New Zealand" => 
    { 
    "2010-10-10" => ["Enter Sandman", "Unforgiven", "And justice for all"]
    }], 
    ["Brisbane Entertainment Centre - Brisbane Qld, Austr..." => 
        { 
        "2010-10-11" => ["Enter Sandman"]
    }]
 }

到目前为止,我想这...不知道如果我在正确的方向移动我..

@venues = Hash.new {|hash, key| hash[key] = 0}
@requests = Request.find_all_by_artist("Metallica")
@requests.each do |request|
  @venues[request.venue] =  request.showdate
end

Answer 1:

下面是一个有效的解决方案:

result = Hash.new {|h1, k1| h1[k1] = Hash.new{|h2, k2| h2[k2] = []}}
Request.find_all_by_artist("Metallica", 
 :select => "DISTINCT venue, showdate, LOWER(song) AS song"
).each do |req|
  result[req.venue][req.showdate] << req.song.titlecase
end


Answer 2:

我想你的结构是不完全正确。 它应该是这样的

[ 
{"Vector Arena - Auckland Central, New Zealand" => 
    { 
    "2010-10-10" => ["Enter Sandman", "Unforgiven", "And justice for all"]
    }}, 
    }"Brisbane Entertainment Centre - Brisbane Qld, Austr..." => 
        { 
        "2010-10-11" => ["Enter Sandman"]
    }}
 ]

试试这个代码

@venues = []
      all_venues = Request.find(:all, :select => "distinct venue, showdate")
      all_venues.each do |unique_venue|
        venue_hash = {}
        showdate_hash = {}
        song_lists = []

        requests = Request.find_all_by_venue(unique_venue.venue)  
        requests.each do |each_request|
          song_lists << each_request.song
        end
        showdate_hash[unique_venue.showdate] = song_lists

        venue_hash[unique_venue.venue] = showdate_hash
        @venues << venue_hash
      end

希望你至少有想法。



文章来源: How do I create this multidemsional Array, Hash Combo?