Recursively convert all numeric strings to integers in a Ruby hash -



Recursively convert all numeric strings to integers in a Ruby hash -

i have hash of random size, may have values "100", convert integers. know can using value.to_i if value.to_i.to_s == value, i'm not sure how recursively in hash, considering value can either string, or array (of hashes or of strings), or hash.

this pretty straightforward recursive implementation (though having handle both arrays , hashes adds little trickiness).

def fixnumify obj if obj.respond_to? :to_i # if can cast fixnum, it. obj.to_i elsif obj.is_a? array # if it's array, utilize enumerable#map recursively phone call method # on each item. obj.map {|item| fixnumify item } elsif obj.is_a? hash # if it's hash, recursively phone call method on each value. obj.merge( obj ) {|k, val| fixnumify val } else # if reason run else, homecoming # unmodified; alternatively throw exception. obj end end

and, hey, 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=>{}}

ruby hash

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -