如何通过密钥有效地合并哈希

时间:2013-08-25 11:05:44

标签: ruby

我有以下数组

 [ {"date"=>"July 2013", "view"=>12245}, 
   {"date"=>"July 2013", "click"=>916}, 
   {"date"=>"August 2013", "view"=>34889}, 
   {"date"=>"August 2013", "click"=>2012} ]

这是所需的输出:

 [ {"date"=>"July 2013", "view"=>12245, "click"=>916},
   {"date"=>"August 2013", "view"=>34889, "click"=>2012} ]

什么是最有效的实施?

1 个答案:

答案 0 :(得分:2)

ar = [ {"date"=>"July 2013", "view"=>12245}, 
   {"date"=>"July 2013", "click"=>916}, 
   {"date"=>"August 2013", "view"=>34889}, 
   {"date"=>"August 2013", "click"=>2012} ]

ar.group_by{|h| h["date"]}.map{|k,v| v.inject(:merge)}
# => [{"date"=>"July 2013", "view"=>12245, "click"=>916},
#     {"date"=>"August 2013", "view"=>34889, "click"=>2012}]