Re: Speaking of eql? (was: Ruby and Java equality usage)

“Robert D.” [email protected] writes:

Note something that’s peripherally related to == and eql? is the
method “hash”, which subclasses MUST override if they override eql?
or == so that the guarantee:

a.eql?(b) implies a.hash == b.hash

is maintained.

I would reword that slightly. You should override hash if you eql?.
But not if you only override ‘==’, as ‘==’ is not involved in hashes or
the hash contract.

Steve

“Molitor, Stephen L” [email protected] writes:

I would reword that slightly. You should override hash if you eql?.
But not if you only override ‘==’, as ‘==’ is not involved in hashes or
the hash contract.

The problem with that is that the default definition of eql? is:

def eql?(other)
self == other
end

So if you override ==, then you need to override either eql? (to have
it mean the same as Object#eql?) or hash.

My very strong recommendation, if you’re only going to override one of
those, would be to override hash (rather than simply overriding eql?
to mean the same as equal?), since otherwise Hash objects with your
objects as key won’t behave properly, and neither will Set s of your
objects.

Daniel M. [email protected] writes:

The problem with that is that the default definition of eql? is:

def eql?(other)
self == other
end

Never mind. I was misled by the html ruby manual on my system which
states:

    eql?(other)
           Checks if two objects are equal. This method is used by
           Hash to compare whether two keys are same. When this
           method is redefined, the hash method should be updated.
           The default definition of the method eql? is like blow:

def eql?(other)
self == other
end

I now wonder what version that manual is from, because the text
doesn’t match what I see on http://ruby-doc.org/core/

That said, now that it’s clear eql? doesn’t work like that, we should
say that redefining == without redefining eql? probably isn’t
something you want to do.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs