ted
ted

Reputation: 5329

Build a kind of hash-tree from arrays

Say we have array of arrays:

tree_limbs = Array.new
tree_limbs << %w(1 2 3 4 5 7)
tree_limbs << %w(1 2 3 4 6)
tree_limbs << %w(1 2 3 8 9 10 11) 
tree_limbs << %w(1 2 3 8 9 10 12)

What's the effective way to build such a hash tree within ruby:

tree_hash = {1 => 
              {2 => 
                {3 => 
                  {4 => 
                    {5 => 
                      {7 => nil}
                    },
                    {6 => nil}
                  },
                  {8 => 
                    {9 => 
                      {10 => 
                        {11 => nil},
                        {12 => nil}
                      }
                    }
                  }
                }
              }
            }

Upvotes: 1

Views: 782

Answers (1)

KL-7
KL-7

Reputation: 47668

If you definitely want explicit nil's on the last level then you can do something like that:

tree_limbs = Array.new
tree_limbs << %w(1 2 3 4 5 7)
tree_limbs << %w(1 2 3 4 6)
tree_limbs << %w(1 2 3 8 9 10 11)
tree_limbs << %w(1 2 3 8 9 10 12)

tree_hash = {}

tree_limbs.each do |path|
  path.each_with_index.inject(tree_hash) do |node, (step, index)|
    if index < path.size - 1
      node[step] ||= {}
    else
      node[step] = nil
    end
  end
end

p tree_hash
#=> {"1"=>{"2"=>{"3"=>{"4"=>{"5"=>{"7"=>nil}, "6"=>nil}, "8"=>{"9"=>{"10"=>{"11"=>nil, "12"=>nil}}}}}}}

Upvotes: 1

Related Questions