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}

This should work fine:

n = Hash[ { |k,v| [k, v.to_i ]}]

my questions are, why are you passing the map in as an array to the Hash method?
Why didn’t the each_value method work?
Is there a way that does not use the Hash method?

This worked:
hash.each {|k,v| hash[k] = v.to_i}

I’d still like to know why the each_value did not. It works in an erb.

Wild guess but I think in both of the cases that worked, we are actually creating a new hash. each_value works as well, except it doesn’t mutate the receiver(v in this case) in place, but creates a new copy instead.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.