将所有数字字符串递归转换为Ruby哈希中的整数 [英] Recursively convert all numeric strings to integers in a Ruby hash
问题描述
我有一个随机大小的哈希,它的值可能像"100"
,我想将其转换为整数.我知道我可以使用value.to_i if value.to_i.to_s == value
来做到这一点,但是考虑到值可以是字符串,也可以是(哈希或字符串的)数组,也可以是其他值,因此我不确定如何在哈希中递归地执行此操作.哈希.
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.
推荐答案
这是一个非常简单的递归实现(尽管必须同时处理数组和哈希值会增加一些棘手的问题).
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=>{}}
这篇关于将所有数字字符串递归转换为Ruby哈希中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!