Converting a nested hash into a flat hash

This question is the inverse of this question.

Given a nested hash like

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

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

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

Answers 1

  • Another way:

    def flat_hash(h,f=[],g={})
      return g.update({ f=>h }) unless h.is_a? Hash
      h.each { |k,r| flat_hash(r,f+[k],g) }
      g
    end
    
    h = { :a => { :b => { :c => 1,
                          :d => 2 },
                  :e => 3 },
          :f => 4 }
    
    flat_hash(h) #=> {[:a, :b, :c]=>1, [:a, :b, :d]=>2, [:a, :e]=>3, [:f]=>4}
    

Related Articles