2014-02-27 57 views
0

相同的键,我想与红宝石相同的密钥来求和阵列哈希内的值,例如:如何总结阵列哈希内的值与红宝石

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

如何使散列的数组是这样的:

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

修复问题使用@sawa回答 – tardjo

回答

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"}] 
+1

谢谢:)泽尝试 – tardjo

-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"}] 
+0

'A = [ {“foo”=>“1”},{“bar”=>“2”}]'。 – sawa

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}] 
+0

Downvoter,并争辩? –

+0

也许这个解决方案不够通用。它不适用于不同的键。 – schmijos

+0

@JosuaSchmid whuch键? –

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}]