Ruby的数组如何.| 比较要素是否相等?

mxc*_*xcl 6 ruby

这是一些示例代码:

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]
Run Code Online (Sandbox Code Playgroud)

它打印2个对象,但它应该打印1个对象.没有调用任何比较方法.Array怎么样.| 比较平等?

sep*_*p2k 6

Array#|是使用哈希实现的.因此,为了使您的类型与它一起使用(以及使用哈希映射和散列集),您必须实现eql?(您已经执行)和hash(您没有).有意义地定义哈希的最直接的方法是返回c.hash.