我有哈希部门
{"Mechnical" => {"boys" => "25", "girls"=>"5"}, "Civil"=> {"boys"=>"18", "girls"=>"12"}}
我想要这样的输出,
{"Mechanical" => "30", "Civil => "30"}
答案 0 :(得分:1)
执行以下操作
# If you are in Ruby 2.1 or greater
your_hash.map { |k,v| [k, v.reduce(0) { |sum, (_, v)| sum + v.to_i }] }.to_h
# => {"Mechnical"=>30, "Civil"=>30}
# below Ruby 2.1
Hash[your_hash.map { |k,v| [k, v.reduce(0) { |sum, (_, v)| sum + v.to_i }] }]
# => {"Mechnical"=>30, "Civil"=>30}
# for all versions
your_hash.each_with_object({}) do |(k,v), h|
h[k] = v.reduce(0) { |sum, (_, v)| sum + v.to_i }
end
# => {"Mechnical"=>30, "Civil"=>30}
答案 1 :(得分:1)
h = { "Mechnical" => {"boys" => "25", "girls"=>"5"},
"Civil"=> {"boys"=>"18", "girls"=>"12"} }
h.map { |k, v| [k, v.values.map(&:to_i).sum] }.to_h
# => {"Mechnical"=>30, "Civil"=>30}
或者
Hash[ h.map { |k, v| [k, v.values.map(&:to_i).sum]} ]
# => {"Mechnical"=>30, "Civil"=>30}
由于您使用的是Rails,sum
可以使用,其他明智的使用inject(:+)