按日期分组和汇总哈希数组

时间:2014-02-03 19:21:16

标签: ruby arrays hash

我有一系列像这样的哈希:

[{:created=>Fri, 22 Jan 2014 13:02:13 UTC +00:00, :amount=>20}, 
{:created=>Fri, 27 Jan 2014 13:14:57 UTC +00:00, :amount=>15}, 
{:created=>Fri, 27 Jan 2014 14:42:40 UTC +00:00, :amount=>10}, 
{:created=>Fri, 28 Jan 2014 15:26:58 UTC +00:00, :amount=>10}, 
{:created=>Fri, 28 Jan 2014 15:30:18 UTC +00:00, :amount=>20}, 
{:created=>Fri, 31 Jan 2014 15:32:46 UTC +00:00, :amount=>50}, 
{:created=>Fri, 31 Jan 2014 15:33:29 UTC +00:00, :amount=>40}]

我想按日期对这些哈希值进行分组,然后对数量进行求和。所以,在我的例子中,输出将是:

[{:created=>"2014-01-22", :amount=>20}, 
{:created=>"2014-01-27", :amount=>25}, 
{:created=>"2014-01-28", :amount=>30}, 
{:created=>"2014-01-31", :amount=>90}]

1 个答案:

答案 0 :(得分:8)

我会这样做:

require 'date'

a = [{:created=> 'Fri, 22 Jan 2014 13:02:13 UTC +00:00', :amount=>20}, 
{:created=>'Fri, 27 Jan 2014 13:14:57 UTC +00:00', :amount=>15}, 
{:created=>'Fri, 27 Jan 2014 14:42:40 UTC +00:00', :amount=>10}, 
{:created=>'Fri, 28 Jan 2014 15:26:58 UTC +00:00', :amount=>10}, 
{:created=>'Fri, 28 Jan 2014 15:30:18 UTC +00:00', :amount=>20}, 
{:created=>'Fri, 31 Jan 2014 15:32:46 UTC +00:00', :amount=>50}, 
{:created=>'Fri, 31 Jan 2014 15:33:29 UTC +00:00', :amount=>40}]

hsh = a.group_by { |h| Date.parse h[:created] }.map do |k,v| 
  {:created => k.to_s,:amount => v.map {|h1| h1[:amount]}.inject(:+)} 
end
hsh
# => [{:created=>"2014-01-22", :amount=>20},
#     {:created=>"2014-01-27", :amount=>25},
#     {:created=>"2014-01-28", :amount=>30},
#     {:created=>"2014-01-31", :amount=>90}]