需要帮助获取嵌套的ruby哈希层次结构

我有哈希深度嵌套哈希,我希望每个键的层次结构(父对子)作为数组。

例如 –

hash = { "properties"=>{ "one"=>"extra", "headers"=>{ "type"=>"object", "type1"=>"object2" }, "entity"=>{ "type"=>"entype" }, }, "sec_prop"=>"hmmm" } 

对于这个哈希,我希望输出如下所示,作为每个键的单独数组。

 [properties,one] [properties,headers,type] [properties,headers,type1] [properties,entity,type] [sec_prop] 

我一直在尝试并通过一些递归方法搜索这个,但它似乎不适合我任何帮助将不胜感激。

这里需要注意的重要一点是,在嵌套中存在相同哈希中的重复键,例如在头和实体中重复键入键。 所以我需要适当的层次结构来识别正确的密钥

我应该只为那些值不是另一个哈希的键得到这个层次结构数组。

它应该采用上面给出的格式,但也欢迎任何其他解决方案

谢谢。!

这是我的尝试:

 hash = { "properties"=>{ "one"=>"extra", "headers"=>{ "type"=>"object", "type1"=>"object2" }, "entity"=>{ "type"=>"entype" }, }, "sec_prop"=>"hmmm" } def fetch_keys(h) h.flat_map do |k,v| if v.is_a?(Hash) fetch_keys(v).map do |keys| [k] + Array(keys) end else k end end end fetch_keys(hash) # => [["properties", "one"], # ["properties", "headers", "type"], # ["properties", "headers", "type1"], # ["properties", "entity", "type"], # "sec_prop"] 

救援的递归:

 def hashkeys(o, keys = [], result = []) if o.is_a?(Hash) o.each do |key, value| hashkeys(value, keys + [key], result) end else result << keys end result end 

这是深度优先搜索,它累积密钥直到它到达叶子(非哈希值)。 每次到达叶子时,它都会将累积的键添加到结果中。

 pp hashkeys(hash) # => [["properties", "one"], # => ["properties", "headers", "type"], # => ["properties", "headers", "type1"], # => ["properties", "entity", "type"], # => ["sec_prop"]]