Ruby: get sum of nested hash value -
i have hash departments
{"mechnical" => {"boys" => "25", "girls"=>"5"}, "civil"=> {"boys"=>"18", "girls"=>"12"}}
i want output this,
{"mechanical" => "30", "civil => "30"}
do below
# if 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} # versions your_hash.each_with_object({}) |(k,v), h| h[k] = v.reduce(0) { |sum, (_, v)| sum + v.to_i } end # => {"mechnical"=>30, "civil"=>30}
Comments
Post a Comment