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

First we need to group it into months. This can be done easiest using .group_by.

hash = Hash[range.group_by { |k,_v| k.to_date.strftime("%Y-%m")}]

Using the same code you already provided, just group_by instead of 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]
  ]
}

Now we need to sum (equivalent to reduce(:+) you tried with a few benefits) them together. We need to modify each value of the hash and sum the last element of each element in the value.

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

returns

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top