这是一些示例代码:
class Obj attr :c,true def == that p '==' that.c == self.c end def <=> that p '<=>' that.c <=> self.c end def equal? that p 'equal?' that.c.equal? self.c end def eql? that p 'eql?' that.c.eql? self.c end end a = Obj.new b = Obj.new a.c = 1 b.c = 1 p [a] | [b]
它打印2个对象,但它应该打印1个对象.没有调用任何比较方法. Array怎么样.|比较平等?
解决方法
阵列#|是使用哈希实现的.因此,为了使您的类型与它一起使用(以及使用哈希映射和散列集),您将必须实现eql? (你做了)和哈希(你没有).有意义地定义哈希的最直接的方法是返回c.hash.