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?
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?
You can use
inject
to sum all the amounts. You can then just put the result back into a hash if you need to.Ruby versions >= 2.4.0 has an Enumerable#sum method. So you can do
array.map { |h| h[:amount] }.sum
This is one way to do it:
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:
Or even just
Note that as @sepp2k pointed out, if you want to get out a
Hash
, you need to wrap it in aHash
again.