Andriy Yurchuk Andriy Yurchuk - 18 days ago 5
Ruby Question

Recursively convert all numeric strings to integers in a Ruby hash

I have a hash of a random size, which may have values like

"100"
, which I would like to convert to integers. I know I can do this using
value.to_i if value.to_i.to_s == value
, but I'm not sure how would I do that recursively in my hash, considering that a value can be either a string, or an array (of hashes or of strings), or another hash.

Answer

This is a pretty straightforward recursive implementation (though having to handle both arrays and hashes adds a little trickiness).

def fixnumify obj
  if obj.respond_to? :to_i
    # If we can cast it to a Fixnum, do it.
    obj.to_i

  elsif obj.is_a? Array
    # If it's an Array, use Enumerable#map to recursively call this method
    # on each item.
    obj.map {|item| fixnumify item }

  elsif obj.is_a? Hash
    # If it's a Hash, recursively call this method on each value.
    obj.merge( obj ) {|k, val| fixnumify val }

  else
    # If for some reason we run into something else, just return
    # it unmodified; alternatively you could throw an exception.
    obj

  end
end

And, hey, it even works:

hsh = { :a => '1',
        :b => '2',
        :c => { :d => '3',
                :e => [ 4, '5', { :f => '6' } ]
              },
        :g => 7,
        :h => [],
        :i => {}
      }

fixnumify hsh
# => {:a=>1, :b=>2, :c=>{:d=>3, :e=>[4, 5, {:f=>6}]}, :g=>7, :h=>[], :i=>{}}
Comments