说我有一个深度嵌套的哈希,例如
data = {
key1: 'foo baz',
arbitary_key2: {
arbitrary_key3: {
unknown_key4: "bar baz",
unknown_key5: "foo qux"
},
key6: "bar qux"
}}
是否有某种方法可以寻找匹配项,并且只检索保留了其祖先的键?
> data.deep_select { |key, value| /bar/i.match?(value) }
# => {
arbitary_key2: {
arbitrary_key3: {
unknown_key4: "bar baz"
}
},
key6: "bar qux"
}
Hashie :: DeepLocate使我如此接近,但仅返回找到结果的叶子,并且在此过程中丢失了父键。如何保存层次结构?
使用https://github.com/evolve75/RubyTree在树上找到一个孩子并获得其祖先。
以下递归方法将返回所需的数组。
def get_em(h,re)
h.each_with_object([]) do |(k,v),arr|
if v.is_a? Hash
a = get_em(v,re)
a.each { |b| arr << [k,*b] } if a.any?
elsif v.match?(re)
arr << [k]
end
end
end
data = {
key1: 'foo baz',
arbitary_key2: {
arbitrary_key3: {
unknown_key4: "bar baz",
unknown_key5: "foo qux"
},
key6: "bar qux"
}
}
get_em(data, /bar/)
#=> [[:arbitary_key2, :arbitrary_key3, :unknown_key4],
# [:arbitary_key2, :key6]]