如何在ruby中使用相同的键对数组哈希中的值求和

时间:2014-02-27 09:02:05

标签: ruby arrays hash

我想在ruby中使用相同的键对数组哈希中的值求和,例如:

a = [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]

如何使哈希数组像这样:

a = [{"nationalvoice"=>"6"}]

4 个答案:

答案 0 :(得分:1)

我的功能解决方案

array = [{"foo" => "1"}, {"bar" => "2"}, {"foo" => "4"}]

array.group_by { |h| h.keys.first }.map do |k, v| 
  Hash[k, v.reduce(0) { |acc, n| acc + n.values.first.to_i }]
end 

# => [{"foo"=>5}, {"bar"=>2}] 

答案 1 :(得分:0)

[{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
.group_by{|h| h.keys.first}.values
.map{|a| {
  a.first.keys.first =>
  a.inject(0){|sum, h| sum + h.values.first.to_i}.to_s
}}
# => [{"nationalvoice"=>"6"}]

答案 2 :(得分:0)

简单方法:

[{ "nationalvoice" => [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}].reduce(0) {|s, v| s + v.values.first.to_i } }]
# => [{"nationalvoice"=>6}]

#replace

a = [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
a.replace( [{ a.first.keys.first => a.reduce(0) {|s, v| s + v.values.first.to_i } }] )
# => [{"nationalvoice"=>6}]

答案 3 :(得分:-1)

我会这样做:

a = [{"nationalvoice"=>"1"}, {"foo" => "1"}, {"bar" => "2"}, {"nationalvoice"=>"5"}] 
new = a.group_by { | h | h.keys.first }.map do |k,v|
     v.each_with_object({}) do | h1,h2|
        h2.merge!(h1) { |key,old,new| (old.to_i + new.to_i).to_s }
     end
end

new # => [{"nationalvoice"=>"6"}, {"foo"=>"1"}, {"bar"=>"2"}]