Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Sum selected hash values

I've got an array of hashes and would like to sum up selected values. I know how to sum all of them or one of them but not how to select more than one key.

i.e.:

[{"a"=>5, "b"=>10, "active"=>"yes"}, {"a"=>5, "b"=>10, "active"=>"no"}, {"a"=>5, "b"=>10, "action"=>"yes"}] 

To sum all of them I using:

t = h.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v + new_v}}
=> {"a"=>15, "b"=>30, "active"=>"yesnoyes"} # I do not want 'active'

To sum one key, I do:

h.map{|x| x['a']}.reduce(:+)
=> 15 

How do I go about summing up values for keys 'a' and 'b'?

like image 783
Digger Avatar asked Dec 16 '22 05:12

Digger


2 Answers

You can use values_at:

hs = [{:a => 1, :b => 2, :c => ""}, {:a => 2, :b => 4, :c => ""}]
keys = [:a, :b]
hs.map { |h| h.values_at(*keys) }.inject { |a, v| a.zip(v).map { |xy| xy.compact.sum }}
# => [3, 6]

If all required keys have values it will be shorter:

hs.map { |h| h.values_at(*keys) }.inject { |a, v| a.zip(v).map(&:sum) }
# => [3, 6]

If you want Hash back:

Hash[keys.zip(hs.map { |h| h.values_at(*keys) }.inject{ |a, v| a.zip(v).map(&:sum) })]
# => {:a => 3, :b => 6}
like image 92
Victor Moroz Avatar answered Dec 30 '22 18:12

Victor Moroz


I'd do something like this:

a.map { |h| h.values_at("a", "b") }.transpose.map { |v| v.inject(:+) }
#=> [15, 30]

Step by step:

a.map { |h| h.values_at("a", "b") }   #=> [[5, 10], [5, 10], [5, 10]]
 .transpose                           #=> [[5, 5, 5], [10, 10, 10]]
 .map { |v| v.inject(:+) }            #=> [15, 30]
like image 42
Stefan Avatar answered Dec 30 '22 17:12

Stefan