According to the Set doc, elements in a set are compared using eql?.
I have a class like:
class Foo
attr_accessor :bar, :baz
def initialize(bar = 1, baz = 2)
@bar = bar
@baz = baz
end
def eql?(foo)
bar == foo.bar && baz == foo.baz
end
end
In console:
f1 = Foo.new
f2 = Foo.new
f1.eql? f2 #=> true
But…
s = Set.new
s << f1
s << f2
s.size #=> 2
Because f1 equals f2, s should not include both of them.
How to make the set reject elements with a custom rule?
The docs that you link to say explicitly (emphasis mine):
If you add a
hashmethod to your class that returns the same value foreql?objects, it works:To be honest I’ve never had a great sense for how to write a good custom
hashmethod when multiple values are involved.