我认为解释这个的最好方法是举个例子:
class A
attr_accessor :test
def initialize(x = nil)
@test = x
end
def ==(other)
return @test == other.test
end
end
a1 = A.new(1) # => #<A:0x11b7118 @test=1>
a1.test # => 1
a2 = A.new(1) # => #<A:0x11fb0f8 @test=1>
a2.test # => 1
a1 == a2 # => true
[a1].include?(a2) # => true
[a1] - [a2] # => [#<A:0x11b7118 @test=1>]
在这个例子中,我如何让[a1] - [a2]返回一个空数组,正如人们所期望的那样,对于任何其他Ruby类?是否有一些我必须为A定义的方法我不知道?
答案 0 :(得分:7)
您需要覆盖eql?
和hash
。这些是用于那些设置操作的那些。
答案 1 :(得分:3)
将这些方法添加到A
def eql?(other)
@test == other.test
end
def hash
@test.hash
end