ruby合并基于键的哈希值数组,并按键/值对的数量排序

时间:2014-04-25 15:06:27

标签: ruby arrays sorting hash

我有这个哈希数组:

ah = [{"Date"=>"2014-03-17", "countdown 7"=>1}, {"Date"=>"2014-03-17", "voice 6"=>1},     
 {"Date"=>"2014-03-18", "voice 1"=>1}, {"Date"=>"2014-03-18", "voice 2"=>0},     
 {"Date"=>"2014-03-18", "voice 3"=>1}, {"Date"=>"2014-03-18", "voice 4"=>0},    
 {"Date"=>"2014-03-18", "voice 5"=>0}, {"Date"=>"2014-03-18", "voice 6"=>0},     
 {"Date"=>"2014-03-19", "voice 5"=>0}, {"Date"=>"2014-03-19", "voice 6"=>0},    
 {"Date"=>"2014-03-20", "countdown 5"=>1}, {"Date"=>"2014-03-20", "voice 7"=>0},     
 {"Date"=>"2014-03-20", "voice 6"=>0}]   

我希望根据密钥合并它:

ah = [{"Date"=>"2014-03-17", "countdown 7"=>1, "voice 6"=>1},      
 {"Date"=>"2014-03-18", "voice 1"=>1, "voice 2"=>0, "voice 3"=>1, "voice 4"=>0, "voice 5"=>0, "voice 6"=>0},       
 {"Date"=>"2014-03-19", "voice 5"=>0, "voice 6"=>0},       
 {"Date"=>"2014-03-20", "countdown 5"=>1, "voice 7"=>0, "voice 6"=>0}]         

试过:

ah.inject { |all, h| all.merge(h) } #no success

有关如何做到这一点的任何提示?

更新
是否可以按键/值对的数量对其进行排序?那么具有最多键/值的散列是第一个,而具有最小键值的散列是最后一个?

输出

[{"Date"=>"2014-03-18", "voice 1"=>1, "voice 2"=>0, "voice 3"=>1, "voice 4"=>0, "voice 5"=>0, "voice 6"=>0},   
 {"Date"=>"2014-03-20", "countdown 5"=>1, "voice 7"=>0, "voice 6"=>0},
 {"Date"=>"2014-03-17", "countdown 7"=>1, "voice 6"=>1},              
 {"Date"=>"2014-03-19", "voice 5"=>0, "voice 6"=>0}       
]       

**更新2 ** 按键长度/值对的长度排序哈希数组:

ah.sort {|a, b| a.length <=> b.length}.reverse  

1 个答案:

答案 0 :(得分:5)

我做:

ah.group_by { |h| h['Date'] }.map { |_,v| v.inject(:update) }
# => [{"Date"=>"2014-03-17", "countdown 7"=>1, "voice 6"=>1},
#     {"Date"=>"2014-03-18",
#      "voice 1"=>1,
#      "voice 2"=>0,
#      "voice 3"=>1,
#      "voice 4"=>0,
#      "voice 5"=>0,
#      "voice 6"=>0},
#     {"Date"=>"2014-03-19", "voice 5"=>0, "voice 6"=>0},
#     {"Date"=>"2014-03-20", "countdown 5"=>1, "voice 7"=>0, "voice 6"=>0}]