Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Can I turn the string values in a ruby hash to an integer?

I created a hash from an array of strings using the Hash[] mehtod. This made all the key value pairs strings: {"green"=>"5", "blue"=>"13", "grass"=>"9"}

Is there now a way to turn the values into an integer? For some reason, each_value is not changing the value to integer as shown here:

y = {"green"=>"5", "blue"=>"13", "grass"=>"9"} n = y.each_value { | v | v = v.to_i } n =>{"green"=>"5", "blue"=>"13", "grass"=>"9"} What I want is to turn it into this: {"green"=>5, "blue"=>13, "grass"=>9}

1 Answer

You can create a new hash and assign the mapped through old hash by for example doing this:

new_hash = Hash[old_hash.map{ |k, v| [k, v.to_i] } ]