Sum the value of array in hash

RubyHash

Ruby Problem Overview


This is my array

[{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2
, :alt_amount=>30}]

i want result

[{:amount => 30}] or {:amount = 30}

Any idea?

Ruby Solutions


Solution 1 - Ruby

Ruby versions >= 2.4.0 has an Enumerable#sum method. So you can do

arr.sum {|h| h[:amount] }

Solution 2 - Ruby

array.map { |h| h[:amount] }.sum

Solution 3 - Ruby

You can use inject to sum all the amounts. You can then just put the result back into a hash if you need to.

arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]    
amount = arr.inject(0) {|sum, hash| sum + hash[:amount]} #=> 30
{:amount => amount} #=> {:amount => 30}

Solution 4 - Ruby

This is one way to do it:

a = {amount:10,gl_acct_id:1,alt_amount:20},{amount:20,gl_acct_id:2,alt_amount:30}
a.map {|h| h[:amount] }.reduce(:+)

However, I get the feeling that your object model is somewhat lacking. With a better object model, you would probably be able to do something like:

a.map(&:amount).reduce(:+)

Or even just

a.sum

Note that as @sepp2k pointed out, if you want to get out a Hash, you need to wrap it in a Hash again.

Solution 5 - Ruby

[{
    :amount=>10,
    :gl_acct_id=>1,
    :alt_amount=>20
},{
    :amount=>20,
    :gl_acct_id=>2,
    :alt_amount=>30
}].sum { |t| t[:amount] }

Solution 6 - Ruby

why not pluck?

ary = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]

ary.pluck(:amount).sum

# for more reliability
ary.pluck(:amount).compact.sum

Solution 7 - Ruby

If we are having only a single element in all the hashes in a array and also keys were different ?

Here is the solution I found:

Sum of the values:

x = [{"a" => 10},{"b" => 20},{"d" => 30}]

Solution:

x.inject(0){|sum, hash| sum+= hash.values.join.to_i }

Also we can do:

x.inject(0){|sum, hash| sum+= hash.values.sum }

Solution 8 - Ruby

total=0
arr = [{:amount=>10, :gl_acct_id=>1, :alt_amount=>20}, {:amount=>20, :gl_acct_id=>2, :alt_amount=>30}]
arr.each {|x| total=total+x[:amount]}
puts total

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionkrunal shahView Question on Stackoverflow
Solution 1 - RubySanthoshView Answer on Stackoverflow
Solution 2 - RubyZsolt HankoView Answer on Stackoverflow
Solution 3 - Rubysepp2kView Answer on Stackoverflow
Solution 4 - RubyJörg W MittagView Answer on Stackoverflow
Solution 5 - RubyLuis TofoliView Answer on Stackoverflow
Solution 6 - RubyAparichithView Answer on Stackoverflow
Solution 7 - RubyYash DubeyView Answer on Stackoverflow
Solution 8 - Rubyghostdog74View Answer on Stackoverflow