我有一个随机大小的哈希值,可能有"100"
之类的值,我想将其转换为整数。我知道我可以使用value.to_i if value.to_i.to_s == value
执行此操作,但我不确定如何在散列中递归执行此操作,因为值可以是字符串,也可以是数组(散列或字符串),或另一个哈希。
答案 0 :(得分:10)
这是一个非常简单的递归实现(虽然必须处理数组和散列都会增加一些技巧)。
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
而且,嘿,它甚至有效:
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=>{}}
答案 1 :(得分:0)
这是我的助手班。它只转换只是数字的字符串(整数或浮点数)。
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"}]]