Converting a hash into a nested hash

后端 未结 6 1720
后悔当初
后悔当初 2020-12-11 07:20

This question is the inverse of this question.

Given a hash that has an array for each key like

{
    [:a, :b, :c] => 1,
    [:a, :b, :d] => 2,         


        
6条回答
  •  独厮守ぢ
    2020-12-11 07:38

    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}}
    

提交回复
热议问题