Converting a hash into a nested hash

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

    Functional recursive algorithm:

    require 'facets'
    
    class Hash
      def nestify
        map_by { |ks, v| [ks.first, [ks.drop(1), v]] }.mash do |key, pairs|
          [key, pairs.first[0].empty? ? pairs.first[1] : Hash[pairs].nestify]
        end
      end
    end
    
    p {[:a, :b, :c]=>1, [:a, :b, :d]=>2, [:a, :e]=>3, [:f]=>4}.nestify
    # {:a=>{:b=>{:c=>1, :d=>2}, :e=>3}, :f=>4}
    

提交回复
热议问题