相同的键,我想与红宝石相同的密钥来求和阵列哈希内的值,例如:如何总结阵列哈希内的值与红宝石
a = [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
如何使散列的数组是这样的:
a = [{"nationalvoice"=>"6"}]
相同的键,我想与红宝石相同的密钥来求和阵列哈希内的值,例如:如何总结阵列哈希内的值与红宝石
a = [{"nationalvoice"=>"5"}, {"nationalvoice"=>"1"}]
如何使散列的数组是这样的:
a = [{"nationalvoice"=>"6"}]
[{"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"}]
谢谢:)泽尝试 – tardjo
我下面做:
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"}]
'A = [ {“foo”=>“1”},{“bar”=>“2”}]'。 – sawa
简单的方法:
[{ "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}]
我功能解决方案
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}]
修复问题使用@sawa回答 – tardjo