从数组构建一种哈希树

时间:2012-06-20 13:58:39

标签: ruby

假设我们有数组数组:

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)

在ruby中构建这样一个哈希树的有效方法是什么:

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

1 个答案:

答案 0 :(得分:1)

如果您确定要在最后一级明确nil,那么您可以这样做:

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