在 Ruby 中,可以使用任何东西作为哈希键:
hash = {
42 => "an integer",
[42, "forty two"] => "an array",
Class => "a class"
}
#⇒ {42=>"an integer", [42, "forty two"]=>"an array", Class=>"a class"}
hash[[42, "forty two"]]
#⇒ "an array"
也就是说,在您的情况下,您可以使用数组[vertex, material]
作为键:
unless vertices.key?([vertex, material])
new_vertices_and_materials << [vertex, material]
vertices[[vertex, material]] = @vertex_index
@vertex_index += 1
end
更红宝石的方法是调用Enumerable#uniq
输入并执行以下操作:
input = [ # example input data
[:vertex1, :material1],
[:vertex2, :material1],
[:vertex2, :material1],
[:vertex2, :material2],
[:vertex2, :material2]
]
new_vertices_and_materials = input.uniq
vertices_and_materials_with_index =
new_vertices_and_materials.
zip(1..new_vertices_and_materials.size).
to_h
#⇒ {[:vertex1, :material1]=>1,
# [:vertex2, :material1]=>2,
# [:vertex2, :material2]=>3}