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?
use Kernel#Integer:
ADDED LATER: With my
y_supportgem, you can make hash operations even more concise.YSupportcan be installed bygem install y_supportand also offersHash#with_keys,Hash#with_values!,Hash#with_keys!that do what you expect they do, andHash#modifythat 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.