迭代嵌套散列中的每个键 [英] iterate over every key in nested hash
本文介绍了迭代嵌套散列中的每个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
module HashNestedGet
refine Hash do
def nested_get key)
返回fetch(key)if has_key?(key)
each | subkey,subval |
如果Hash ===子类型
结果= subval.nested_get(键)
返回结果如果结果
结束
结束
结束
结束
end
end
a = {b:1,c:{d:{e:2}}}
使用HashNestedGet
require'pp'
pp a.nested_get(:b)
#=> 1
pp a.nested_get(:e)
#=> 2
pp a.nested_get(:d)
#=> nil
(作为细化发布,所以它在 irb
;如果有必要,很容易变成一个普通函数)
Is there a simple way to iterate over every key in a nested hash. I have a large json and I just want the values of certain keys, no matter what level they are at. It also doesn't matter who their parent is. Looking for a way to just straight line iterate though each key and return the values of keys that equal a specific string.
解决方案
module HashNestedGet
refine Hash do
def nested_get(key)
return fetch(key) if has_key?(key)
each do |subkey, subval|
if Hash === subval
result = subval.nested_get(key)
return result if result
end
end
nil
end
end
end
a = { b: 1, c: { d: { e: 2 } } }
using HashNestedGet
require 'pp'
pp a.nested_get(:b)
# => 1
pp a.nested_get(:e)
# => 2
pp a.nested_get(:d)
# => nil
(posted as refinement, so it won't work in irb
; easy enough to make into a plain function if necessary)
这篇关于迭代嵌套散列中的每个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文