我以为这就是答案,但它仍然把三个留在里面。
array.uniq
# => ["0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "3"]
您可以传递uniq
一个块,您可以使用它来转换项目以检查唯一性。
array.uniq {|i| i.to_s}
您需要将元素转换为整数(或字符串)以进行比较:
array.map(&:to_i).uniq
也许你可以看看下面的方法
ruby-1.9.3-p0 :020 > arr = ["0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "3"]
=> ["0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "3"]
ruby-1.9.3-p0 :021 > arr.map(&:to_i).uniq
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ruby-1.9.3-p0 :022 > arr.uniq(&:to_i)
=> ["0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ruby-1.9.3-p0 :023 > arr.uniq(&:to_s)
=> ["0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]