如何将 ruby 文字散列按 year/moth 和求和值

How group ruby literal hash by year/moth and sum values

我有以下散列,我想按 year/month 分组并对值求和:

range = {
"2020-11-06 00:00:00 +0000" => 234100.14176395803,
"2020-11-07 00:00:00 +0000" => 57731.63072153537,
"2020-11-08 00:00:00 +0000" => 68903.8902730576,
"2020-11-09 00:00:00 +0000" => 180971.98008691627,
........
"2021-02-01 00:00:00 +0000" => 169004.96299567595,
"2021-02-02 00:00:00 +0000" => 183363.9687217272,
"2021-02-03 00:00:00 +0000" => 200400.2505103338
}

我能做组:hash = Hash[range.collect { |k,v| [k.to_date.strftime("%Y-%m"), v]}]但我无法获得值总和,值结果和哈希收集只是最后一天。

{
"2020-11" => 155346.83103528828,
"2020-12" => 175424.41029800082,
"2021-01" => 55366.44438577791,
"2021-02" => 200400.2505103338
}

使用 reduce 方法 hash.values.reduce(:+) 我可以获得总值,但我需要按年按月计算。

您可以通过 each_with_object:

构建一个新的散列
range.each_with_object(Hash.new(0)) { |(k, v), h| h[k[0, 7]] += v }
#=> {"2020-11"=>541707.6428454672, ..., "2021-02"=>552769.1822277369}

代替k[0, 7]你也可以使用k.to_date.strftime('%Y-%m')

首先我们需要把它分成几个月。这可以使用 .group_by.

最简单地完成
hash = Hash[range.group_by { |k,_v| k.to_date.strftime("%Y-%m")}]

使用您已经提供的相同代码,只是 group_by 而不是 collect

{
  "2020-11"=>[
    ["2020-11-06 00:00:00 +0000", 234100.14176395803],
    ["2020-11-07 00:00:00 +0000", 57731.63072153537],
    ["2020-11-08 00:00:00 +0000", 68903.8902730576],
    ["2020-11-09 00:00:00 +0000", 180971.98008691627]
  ],
  "2021-02"=>[
    ["2021-02-01 00:00:00 +0000", 169004.96299567595],
    ["2021-02-02 00:00:00 +0000", 183363.9687217272],
    ["2021-02-03 00:00:00 +0000", 200400.2505103338]
  ]
}

现在我们需要 sum(等同于 reduce(:+) 您尝试过一些好处)它们在一起。我们需要修改哈希的每个值,并对值中每个元素的最后一个元素求和。

hash.transform_values {|a| a.sum(&:last) }

returns

{
  "2020-11" => 541707.6428454673,
  "2021-02" => 552769.1822277369
}