Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively convert all numeric strings to integers in a Ruby hash

Tags:

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.

like image 848
Andrii Yurchuk Avatar asked Jan 16 '12 09:01

Andrii Yurchuk


People also ask

Can a ruby hash key be an integer?

Integers are objects in Ruby, so are Hashes for that matter so you could use Hashes as keys.


2 Answers

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=>{}}
like image 172
Jordan Running Avatar answered Sep 29 '22 06:09

Jordan Running


This is my helper class. It only converts Strings which are just numbers (Integer or Float).

module Helpers
  class Number
    class << self
      def convert(object)
        case object
        when String
          begin
            numeric(object)
          rescue StandardError
            object
          end
        when Array
          object.map { |i| convert i }
        when Hash
          object.merge(object) { |_k, v| convert v }
        else
          object
        end
      end # convert

      private

      def numeric(object)
        Integer(object)
      rescue
        Float(object)
      end # numeric
   end # << self
  end # Number
end # Helpers

Helpers::Number.convert [{a: ["1", "22sd"]}, 2, ['1.3', {b: "c"}]]
#=> [{:a=>[1, "22sd"]}, 2, [1.3, {:b=>"c"}]]
like image 44
Ali Aminfar Avatar answered Sep 29 '22 08:09

Ali Aminfar