Sum the value of array in hash

Viewed 72520

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?

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

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

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 }

Related