I think the best way to explain this is with an example:
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>]
In this example, how would I get [a1] - [a2] to return an empty array, as one would expect it to for any other Ruby class? Is there some method that I have to define for A that I'm missing?
You need to override eql?
and hash
. These are the ones that are used for those kinds of set operations.
Add these methods to A
def eql?(other)
@test == other.test
end
def hash
@test.hash
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With