Ruby:Sum选择哈希值

时间:2013-09-25 11:53:34

标签: ruby arrays hash ruby-on-rails-4 inject

我有一系列哈希值,想总结选定的值。我知道如何总结所有这些或其中一个而不是如何选择多个密钥。

即:

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

总结我使用的所有内容:

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'

总结一把钥匙,我这样做:

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

如何总结键'a'和'b'的值?

3 个答案:

答案 0 :(得分:7)

您可以使用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]

如果所有必需的键都有值,则它会更短:

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

如果你想要Hash回复:

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

答案 1 :(得分:3)

我会做这样的事情:

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

一步一步:

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]

答案 2 :(得分:2)

这是怎么回事?

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}