I have an array of hashes in Ruby:
array = [
{:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
:value => 200}
{:date => Wed, 04 May 2011 01:00:00 PDT -07:00,
:value => 100}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 300}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 150}
]
I would like to be able to combine the values every day so that I have a new array:
array = [
{:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
:value => 300}
{:date => Tue, 03 May 2011 00:00:00 PDT -07:00,
:value => 450}
]
What is the most elegant way to find an array per day and summarize the values for each day?
This is what I originally tried:
entries = [
{:date => Wed, 04 May 2011 00:00:00 PDT -07:00,
:value => 200}
{:date => Wed, 04 May 2011 01:00:00 PDT -07:00,
:value => 100}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 300}
{:date => Tue, 03 May 2011 01:00:00 PDT -07:00,
:value => 150}
]
first_day = 29.days.ago.beginning_of_day
total_days = 30
day_totals = (0...total_days).inject([]) do |array, num|
startat = first_day + num.day
endat = startat.end_of_day
total_value_in_day = entries.where("date >= ? and date <= ?", startat, endat).sum(:value)
array << {:date => startat, :value => total_value_in_day}
end
I realized that my mistake was with a method wherethat is a Rails method for finding objects and cannot be used on arrays. So, my main question is: is there a way to search for arrays or hashes with conditions.