我有this data,我需要输出类似这种类型的输出..我基本上需要拥有所有场地和他们的日期以及与他们相关的所有歌曲....如果有人能想到一个更好的结构以及如何实现它我会非常感激...
{
["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
答案 0 :(得分:1)
我认为你的结构并不完全正确。它应该像
[
{"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
希望你至少得到这个想法。
答案 1 :(得分: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