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

integerrubystringtype conversion

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:

"Feline".to_i
# => 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?

Best Answer

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 }