我有以下数组
[ {"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} ]
什么是最有效的实施?
答案 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}]