在获取嵌套红宝石哈希层次结构方面需要帮助 [英] need help in getting nested ruby hash hierarchy

查看:71
本文介绍了在获取嵌套红宝石哈希层次结构方面需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have hash deep nested hash and i want the hierarchy(parent to child) for each key as an array.

例如-

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

对于此哈希,我希望将以下给出的输出作为每个键的单独数组.

for this hash I want output as given below, as a separate array for each key.

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

我一直在尝试通过一些递归方法进行搜索,但是似乎对我没有用,将不胜感激.

i have been trying and searching this for so long through some recursive methods but it doesn't seems to work for me any help will be appreciated.

这里要注意的重要事情是,与嵌套相同的哈希中有重复的键 例如,在标题和实体中都重复输入type key. 这样我就需要适当的层次结构来标识适当的密钥

important thing to notice here is there are duplicate keys in the same hash as a nesting for example type key is repeated in both headers and entity. so that i need proper hierarchy to identify the proper key

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

and i should get this array of hierarchy only for those keys whose value is not a another hash.

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

It should be in the format above given but any other solutions also welcome

谢谢.!

推荐答案

这是我的尝试:

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

这篇关于在获取嵌套红宝石哈希层次结构方面需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆