Yshmarov
Yshmarov

Reputation: 3729

Sum of value in all hashes

How can I sum the amount of all payments?

My setup:

# payment.rb

# metadata: text
store :metadata, accessors: [:product, :amount]

Results in:

Payment.all
#=> [id: 1, metadata: {product: "a", amount: 10}], [id: 2, metadata: {product: "b", amount: 15}]
Payment.first.metadata[:amount]
#=> 10
Payment.map(&:metadata[:amount]).sum
#=> DOES NOT WORK (25 expected)

Upvotes: 0

Views: 74

Answers (3)

Kaiizer
Kaiizer

Reputation: 81

There is 2 methods with ActiveRecordsRelation SUM & PLUCK like shown in others answers.

but I advise you to use SUM it is easier to remember

Upvotes: 0

Ritesh Choudhary
Ritesh Choudhary

Reputation: 782

You can use pluck for get only metadata then use inject for sum like below

Payment.pluck(:metadata).inject(0) { |sum, h| sum + h[:amount] }

Upvotes: 2

akerr
akerr

Reputation: 375

You can call the sum method on an array, so if you use Payments.all you'll have an array of all your payments and then should be able to use the sum for the amounts on each object. It is on the Enumerable class as well as the Array class.

Payment.all.sum { |p| p.metadata[:amount] } or Payment.all.sum(&:metadata[:amount])

Upvotes: 1

Related Questions