1

假设我们有数组数组:

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

1 回答 1

1

如果您绝对希望nil在最后一级明确地使用 's,那么您可以执行以下操作:

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}}}}}}}
于 2012-06-20T14:13:45.157 回答