pyfl88 pyfl88 - 6 months ago 21
Ruby Question

Sum the next value of hash in an array of hashes

I have an array of hashes like this:

[{Mon, 09 May 2016 14:49:17 UTC +00:00=>12},
{Sun, 17 Apr 2016 14:08:40 UTC +00:00=>30},
{Sun, 16 Apr 2016 14:08:40 UTC +00:00=>18},
{Sun, 15 Apr 2016 14:03:33 UTC +00:00=>21}]


How can I sum the previous value from the oldest date to the current date, my expected output will be:

[{Mon, 09 May 2016 14:49:17 UTC +00:00=>81},
{Sun, 17 Apr 2016 14:08:40 UTC +00:00=>69},
{Sun, 16 Apr 2016 14:08:40 UTC +00:00=>39},
{Sun, 15 Apr 2016 14:03:33 UTC +00:00=>21}]


Thanks!

Answer

Assuming that the key of every hash in your array is a DateTime object, you can get what your want with this:

balance = [
  {DateTime.parse('Mon, 09 May 2016 14:49:17 UTC +00:00')=>12}, 
  {DateTime.parse('Sun, 17 Apr 2016 14:08:40 UTC +00:00')=>30}, 
  {DateTime.parse('Sun, 16 Apr 2016 14:08:40 UTC +00:00')=>18}, 
  {DateTime.parse('Sun, 15 Apr 2016 14:03:33 UTC +00:00')=>21}
] # => your original array     

# Get expected array.
balance.map{ |h| 
  { 
    h.keys.first => balance.select{ |e| 
                      e.keys.first <= h.keys.first }.map{ |s| 
                        s[s.keys.first] }.reduce(:+) 
  } 
} 

I split the code in lines in order to improve readability.