Reputation: 170
Having pulled donations from the past two years, I'm trying to derive the sum of those donations per month (a total of 24 sums), storing the keys (each month) and the values (the sum of donations for each month) in an array of hashes.
Here's what I've got so far:
@donations = Gift.between(Date.today - 2.years, Date.today, :field => gift_date)
@donations.each do |donation|
#logic here that puts gift_amount into the right month (of the 24 months)
# and adds it to the previous balance for that month, ending up with 24 keys
# and sum values.
end
How can I do this in Ruby/Rails?
Upvotes: 2
Views: 154
Reputation: 7725
Continuing where @mbratch left off:
donations = Gift.where(:date => (Date.today - 2.years)..Date.today)
Hash[donations.group_by { |d| [d.date.year, d.date.month] }
.map do |year_month, donations|
[year_month, donations.map(&:amount).reduce(:+)]
end]
Upvotes: 2
Reputation: 58244
donation_hash = Hash.new(0)
Gift.where(:gift_date => (Date.today - 2.years)..Date.today).each do |donation|
donation_hash[[donation.gift_date.month, donation.gift_date.year]] += donation.amount
end
This will create a hash with keys of [month, year]
and value of total amount donated for that month/year. There are probably a few other suitable ways to create a key which meets the need of your application.
Upvotes: 0