试试这个:
incoming = [ {:date => 20090501, :width => 2},
{:date => 20090501, :height => 7},
{:date => 20090501, :depth => 3},
{:date => 20090502, :width => 4},
{:date => 20090502, :height => 6},
{:date => 20090502, :depth => 2},
]
# Grouping by `:date`
temp = {}
incoming.each do |row|
if temp[row[:date]].nil?
temp[row[:date]] = []
end
temp[row[:date]] << row
end
# Merging it together
outcoming = []
temp.each_pair do |date, hashlist|
res = {}
hashlist.each do |hash|
res.merge!(hash)
end
outcoming << res
end
有关hash
-members 的信息,请参阅此页面
当排序很重要时,您必须使用锯齿状数组:
incoming = [ {:date => 20090501, :width => 2},
{:date => 20090501, :height => 7},
{:date => 20090501, :depth => 3},
{:date => 20090502, :width => 4},
{:date => 20090502, :height => 6},
{:date => 20090502, :depth => 2},
]
# Grouping by `:date`
temp = {}
incoming.each do |row|
if temp[row[:date]].nil?
temp[row[:date]] = []
end
key = row[:date]
row.delete :date
temp[key] << row
end
# Merging it together
outcoming = []
temp.each_pair do |date, hashlist|
res = [:date, date]
hashlist.each do |hash|
hash.each_pair {|key, value| res << [key, value] }
end
outcoming << res
end