Ron Green pisze:
Here is an example:
a class whose instances have always the same #hash and #eql? which
always returns true
class Foo
def hash
puts "hash called"
0
end
def eql? other
puts "eql? called"
true
end
end
h = {}
f1 = Foo.new
f2 = Foo.new
# given
h[f1] = :blah
here, f1.hash is used to locate the bucket to be inserted into, so it
will only output "hash called".
h[f1]
here, the f1.hash is used to locate the bucket and then references will
be compared (f1 is identical to f1 so eql? won't have to be called).
h[f2]
here, the f2.hash is used to locate the bucket, it will be found, but f2
is not identical to f1, so eql? method will have to be used (which in
turn returns true, so the objects are considered equal) and finally the
lookup will be successfull.
In a hash, when two different objects return the same hash value, it's
called a collision. Equality operation here just atcs like a guard to
make sure we are dealing with right object.
lopex