0

我有以下数组

 [ {"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} ]

什么是最有效的实施方式?

4

1 回答 1

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}]
于 2013-08-25T11:08:54.100 回答