下面是一些示例代碼: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]
它打印2個對象,但它應該打印1個對象。沒有任何比較方法被調用。 Array如何。|比較平等?
只是爲了確認 - Ruby的Array#散列方法是否保證值相等當且僅當數組內容相等? – 2011-12-23 23:23:17
@EricWalker號它保證兩個陣列hashs相等如果(但不是僅當)兩個陣列包含具有以相同的順序相同的散列值的元素。然而,這與這個問題無關,因爲這裏只對元素調用hash,而不是在數組本身。 – sepp2k 2011-12-23 23:27:51