2

I'm looking to perform a conversion of the values in a Ruby hash from String to Integer.

I thought this would be fairly similar to the way you perform a conversion in a Ruby array (using the map method), but I have not been able to find an elegant solution that doesn't involve converting the hash to an array, flattening it, etc.

Is there a clean solution to do this?

Eg. From

x = { "a" => "1", "b" => "2", "c"=> "3" }

To

x = { "a" => 1, "b" => 2, "c" => 3 }

4 Answers 4

4

To avoid modifying the original Hash (unlike the existing answers), I'd use

newhash = x.reduce({}) do |h, (k, v)|
  h[k] = v.to_i and h
end

If you're using Ruby 1.9, you can also use Enumerable#each_with_object to achieve the same effect a bit more cleanly.

newhash = x.each_with_object({}) do |(k, v), h|
  h[k] = v.to_i
end

If you want to, you can also extract the logic into a module and extend the Hash class with it.

module HMap
  def hmap
    self.each_with_object({}) do |(k, v), h|
      h[k] = yield(k, v)
    end
  end
end

class Hash
  include HMap
end

Now you can use

newhash = x.hmap { |k, v| v.to_i } # => {"a"=>1, "b"=>2, "c"=>3}
Sign up to request clarification or add additional context in comments.

1 Comment

Great thorough answer, very well detailed.
3

My preferred solution:

Hash[x.map { |k, v| [k, v.to_i]}] #=> {"a"=>1, "b"=>2, "c"=>3}

A somewhat wasteful one (has to iterate over the values twice):

Hash[x.keys.zip(x.values.map(&:to_i))] #=> {"a"=>1, "b"=>2, "c"=>3}

2 Comments

thanks! this solution seems like the one i would use. I thought there would be something that used the map function.
Note that this answer creates an intermediate Array (Enumerable#map always returns an Array), so for big Hashes it's better to use my solution.
2

Try this:

x.each{|k,v| x[k]=v.to_i}

Comments

0
p.keys.map { |key| p[key] = p[key].to_i }

3 Comments

This doesn't work. The block parameters are in the wrong place and neither Array or Enumerable have a method called to_map.
p.keys.map { |key| p[key] = p[key].to_i } is what you meant.
to_map was my custom method.. just forgot that.. thanks for correction

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.