Reputation: 10350
Here is a nested hash. We want to add all the value of "subtotal" together in ruby's way. Please be noted that the key of "0" and "1342119042142" could be any other unknown strings (number of keys is at least one. Could be more than one) when performing the addition.
{"0"=>{"lease_item_id"=>"3",
"subtotal"=>"100"},
"1342119042142"=>{"lease_item_id"=>"1",
"subtotal"=>"100",
"_destroy"=>"false"}}}
Thanks.
Upvotes: 3
Views: 1733
Reputation: 9146
hash = {"0"=>{"lease_item_id"=>"3", "subtotal"=>"100"}, "1342119042142"=>{"lease_item_id"=>"1", "subtotal"=>"100", "_destroy"=>"false"}}
sum = hash.values.reduce(0){|sum,inner| sum + inner["subtotal"].to_i }
Upvotes: 1
Reputation: 5982
Like this:
set up hash:
s = {"0"=>{"lease_item_id"=>"3", "subtotal"=>"100"},
"1342119042142"=>{"lease_item_id"=>"1", "subtotal"=>"100","_destroy"=>"false"}}
calculate total:
total = s.inject(0) { |i, j| i + j.last["subtotal"].to_i}
Explanation: Look here for documentation. Basically inject
is given an initial value (in the above code it is 0) and it passes the given value to the given block, where it gets set to what is returned from the block in each iteration. So in the above code, initially it is 0, on the first iteration it is set to 0 + 100
and now is equal to 100, and on the second [and final] iteration it is set to 100 + 100
, 200.
Upvotes: 3
Reputation: 1492
Assuming h is your hash and the subtotal can be decimal value:
h.values.sum{|x| x['subtotal'].to_f}
Upvotes: 2