Andriy Yurchuk Andriy Yurchuk - 1 year ago 68
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

, 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 Source

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.

  elsif obj.is_a? Array
    # If it's an Array, use Enumerable#map to recursively call this method
    # on each item. {|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 }

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


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=>{}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download