Recursively convert all numeric strings to integer

2019-05-03 08:44发布

问题:

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.

回答1:

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=>{}}


回答2:

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"}]]


标签: ruby hash