将散列转换为嵌套散列 [英] Converting a hash into a nested hash

查看:101
本文介绍了将散列转换为嵌套散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与这个问题相反。

给定一个散列,每个键都有一个数组,例如

Given a hash that has an array for each key like

{
    [:a, :b, :c] => 1,
    [:a, :b, :d] => 2,
    [:a, :e] => 3,
    [:f] => 4,
}

将其转换为嵌套哈希的最佳方式是

what is the best way to convert it into a nested hash like

{
    :a => {
       :b => {:c => 1, :d => 2},
       :e => 3,
    },
    :f => 4,
}


推荐答案

,一个递归的留给练习读者:

Here's an iterative solution, a recursive one is left as an exercise to the reader:

def convert(h={})
  ret = {}
  h.each do |k,v|
    node = ret
    k[0..-2].each {|x| node[x]||={}; node=node[x]}
    node[k[-1]] = v
  end
  ret
end

convert(your_hash) # => {:f=>4, :a=>{:b=>{:c=>1, :d=>2}, :e=>3}}

这篇关于将散列转换为嵌套散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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