1

i have hash departments

{"Mechnical" => {"boys" => "25", "girls"=>"5"}, "Civil"=> {"boys"=>"18", "girls"=>"12"}}  

i want output like this,

{"Mechanical" => "30", "Civil => "30"}

2 Answers 2

2

Do as below

# 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}
Sign up to request clarification or add additional context in comments.

Comments

2
hsh = { "Mechnical" => {"boys" => "25", "girls"=>"5"}, "Civil"=> {"boys"=>"18", "girls"=>"12"} } 

hsh.map { |d, s| [d, s.sum {|_, c| c.to_i} ] }.to_h
# => {"Mechnical"=>30, "Civil"=>30}

If count is a number rather than a String, you can do

hsh.map { |d, s| [d, s.sum(&:last) ] }.to_h
# => {"Mechnical"=>30, "Civil"=>30}

Since you are using Rails, sum will work, other wise use inject(:+)

Thanks Arup for pointing out the redundancy of 2 intermediate arrays.

EDIT

Ruby has Enumerable#sum since 2.4.0

1 Comment

Why did you suggest 2 extra intermediate arrays ? (v.values.map(&:to_i))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.