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

Gau*_*v24 3 ruby arrays hash

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

例如 -

 hash = {
"properties"=>{
    "one"=>"extra",
    "headers"=>{
        "type"=>"object",
        "type1"=>"object2"
    },
    "entity"=>{
        "type"=>"entype"
    },       
},
"sec_prop"=>"hmmm"
}
Run Code Online (Sandbox Code Playgroud)

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

[properties,one]
[properties,headers,type]
[properties,headers,type1]
[properties,entity,type]
[sec_prop]
Run Code Online (Sandbox Code Playgroud)

通过一些递归方法,我一直在尝试和搜索这么久但它似乎对我没有任何帮助将不胜感激.

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

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

它应采用上述格式,但欢迎任何其他解决方案

谢谢.!

Way*_*rad 5

救援的递归:

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
Run Code Online (Sandbox Code Playgroud)

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

pp hashkeys(hash)
# => [["properties", "one"],
# =>  ["properties", "headers", "type"],
# =>  ["properties", "headers", "type1"],
# =>  ["properties", "entity", "type"],
# =>  ["sec_prop"]]
Run Code Online (Sandbox Code Playgroud)