对象散列的 Ruby 递归映射 [英] Ruby recursive map of a hash of objects
问题描述
我有一个散列,它有一个未知的集合以及嵌套数组、散列、散列数组和字符串的混合.这是 JSON.parse
的结果.数据的结构必须与它开始时的结构相同.最终目标是将字符串转换为可能是 Fixnums 的 Fixnums.
I have a hash that has an unknown collection and mixture of nested arrays, hashes, arrays of hashes and strings. This is the result of JSON.parse
. The structure of the data must be the same as it started with. The end goal is to convert strings to Fixnums that could be Fixnums.
以下工作正常,但我想知道是否可以缩短.请注意我如何需要 clean
方法中的键和值,因为并非所有可以是 Fixnums 的字符串都应该是.有什么想法吗?
The following works just fine, but I was wondering if it could be shortened. Note how I need the key and the value in the clean
method as not all strings that can be Fixnums should be. Any ideas?
def clean_node(node)
if node.class == String
clean(node)
elsif node.class == Array
node.each_with_index do |obj, i|
if obj.class == String
node[i] = clean(node[i], obj)
else
clean_node(obj)
end
end
elsif node.class == Hash
node.each_pair do |key, value|
if value.class == String
node[key] = clean(key, value)
else
clean_node(value)
end
end
end
end
def clean(key, value)
FIXNUM_KEYS.include?(key)? value.to_i : value
end
推荐答案
虽然我没有研究过递归,但我必须评论一个事实,即您正在编写 if 语句在 case 语句中更易于阅读:
Although I have not looked into the recursion, I must comment on the fact that you are writing if statements that would be easier to read in a case statement:
def clean_node(node)
case node
when String then clean(node)
when Array
node.each_with_index do |obj, i|
case obj
when String
node[i] = clean(node[i], obj)
else
clean_node(obj)
end
end
when Hash....
这篇关于对象散列的 Ruby 递归映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!