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)

ルビー内でそのようなハッシュツリーを構築する効果的な方法は何ですか?

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

1 に答える 1

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