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.
是否有一种简单的方法来迭代嵌套哈希中的每个键。我有一个大的json,我只想要某些键的值,无论它们处于什么级别。他们的父母是谁也没关系。寻找直线的方法迭代每个键并返回等于特定字符串的键的值。
1 个解决方案
#1
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)
(作为细化发布,因此它不会在irb中工作;如果需要,很容易变成普通函数)
#1
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)
(作为细化发布,因此它不会在irb中工作;如果需要,很容易变成普通函数)