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

时间:2014-03-11 17:16:47

标签: ruby arrays hash

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

例如 -

 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]

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

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

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

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

感谢!

2 个答案:

答案 0 :(得分: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

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

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

答案 1 :(得分:1)

这是我的尝试:

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"]