Minmal testcase:
class C
def hash
3
end
end
[C.new, C.new].uniq
=> [#<C:0x00000003a05098>, #<C:0x00000003a05070>]
根据the 1.9.3 Array#uniq docs,它应删除重复项。在源代码中,它从数组创建哈希,循环哈希,并将每个哈希值添加到新数组中以返回。此类C为所有对象返回相同的哈希键(您可以通过在其中抛出puts
来看到它被调用),但uniq
返回的数组未进行重复数据删除。
uniq
的定义是否还有其他内容?绝对不是==
为项目返回true。
答案 0 :(得分:5)
Array#uniq
依赖于hash
和eql?
进行比较:
class C
def hash
3
end
def eql?( c )
self.hash == c.hash
end
end
[C.new, C.new].uniq # #<C:0x00000000c70498>
注意:如果您要重载eql?
,那么您还应该重载==
。插入类定义:
alias :== :eql?
然后按预期评估:
C.new == C.new # => true