How to convert only strings hash values that are numbers to integers

I have rows of hashes imported from several different XML database dumps that look like this (but with varying keys):

{"Id"=>"1", "Name"=>"Cat", "Description"=>"Feline", "Count"=>"123"}

I tried using #to_i but it converts a non-number string to 0:

# => 0

But what I'd like is a way for "Feline" to remain a string, while Id and Count in the above example become integers 1 and 123.

Is there an easy way to convert only the strings values that are numbers into integers?


use Kernel#Integer:

my_hash = {"Id"=>"1", "Name"=>"Cat", "Description"=>"Feline", "Count"=>"123"}
Hash[{ |a, b| [ a,
                              Integer b
                            rescue ArgumentError
                            end ] } ]

ADDED LATER: With my y_support gem, you can make hash operations even more concise.

require 'y_support/core_ext/hash'
my_hash.with_values { |v| begin
                            Integer b
                          rescue ArgumentError
                          end }

YSupport can be installed by gem install y_support and also offers Hash#with_keys, Hash#with_values!, Hash#with_keys! that do what you expect they do, and Hash#modify that expects a binary block returning a pair of values, modifying the hash in place. There have been proposals to add such methods directly to the Ruby core in the future.

One line answer: Using regex approach

h.merge(h) { |k, v| v.match(/\A[+-]?\d+?(\.\d+)?\Z/) ? v.to_i : v }

Using Integer approach

h.merge(h) { |k, v| Integer(v) rescue v }

Need Your Help

Is there a good NumPy clone for Jython?

java python numpy jython

I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and