Converting a hash into a nested hash

后端 未结 6 1726
后悔当初
后悔当初 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:31

    Another way:

    def convert(h)
      h.each_with_object({}) { |(a,n),f| f.update({ a.first=>(a.size==1 ? n :
        convert({ a[1..-1]=>n })) }) { |_,ov,nv| ov.merge(nv) } }
    end
    

    Try it:

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

提交回复
热议问题