Ruby: sum of selected hash values

I have an array of hashes and would like to summarize the selected values. I know how to summarize 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 summarize all of them, I use:

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 summarize one key, I do:

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

How can I sum the values ​​for the keys "a" and "b"?

+4
source share
3 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 the necessary keys are relevant, they will be shorter:

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

If you want Hashback:

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

I would 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]
+3
source

?

h = [{"a"=>5, "b"=>10, "active"=>"yes"}, {"a"=>5, "b"=>10, "active"=>"no"}, {"a"=>5, "b"=>10, "action"=>"yes"}]
p h.map{|e| e.reject{|k,v| %w(active action).include? k } }.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v + new_v}}
# >> {"a"=>15, "b"=>30}
+2

All Articles