0

I have an array of transactions, each looks like this...

Transaction:0xc3b8de4 @id="p5qvzdyQZeTyKk97ozbAhAeN0DwVgMh6re13Z", @account="N08xNQywYVUZaqoN9bwAI6BbeBrzyAfKmpzQe", @date="2014-02-03", @amount=100, @name="COMED 4131 Reference#", @meta={"is_risky"=>false, "location"=>{"store_number"=>"10818"}}, @location=nil, @pending=false, @score={"location"=>{}, "name"=>0.2}, @type={"primary"=>"unresolved"}, @category=nil, @category_id=nil>]} 

I want to group the transactions by month so I have this...

@income_by_month = @payroll_transactions.group_by { |t| t.date.to_date.month })

Which groups the transactions by month.

Now I need a sum of the "amount" object in each months transactions. So I need the total of all amount for each month. Here is what I have so far but I have not been successful.

@payroll_transactions = @user.transactions.find_all { |t| t.category_id == '21009000' } #finds all payroll transactions for all months
@income_by_month = @payroll_transactions.group_by { |t| t.date.to_date.month }) #groups transactions into month groups
@income_by_month.map(&:amount).inject(0, &:+) #I need a method to sum the total of amounts for each month

Thanks in advance

2 Answers 2

1

This should do:

@income_by_month = @payroll_transactions.group_by { |t| t.date.to_date.month }).map do |month, transactions|
  [month, transactions.sum(&:amount)]
end.to_h
0
0

What about this? compact removes nil values, don't know if you'd need that or not.

@income_by_month.map(&:amount).compact.reduce(&:+)

You might need a @income_by_month.month(:april).map... if I understand you correctly, and you may still need to implement that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.