Why does the eql? method exist?

  • Thread starter Just Another Victim of the Ambient Morality
  • Start date
J

Just Another Victim of the Ambient Morality

Not too long ago, there was a thread about a bug in Ruby where vectors
(which turned out to be derived from matrices) failed to work as hash keys.
The problem turned out to be a typo in the definition of the Matrix class.
The method "eql?" is used by hashes for key comparison but, in the Matrix
class, this method was named "eqn?" by mistake.
This got me thinking about the role of the "eql?" method. Why does it
exist? What is the Ruby rationale behind having two different equality
methods, namely "==" and "eql?"
Thank you...
 
E

Esad Hajdarevic

Just said:
This got me thinking about the role of the "eql?" method. Why does it
exist? What is the Ruby rationale behind having two different equality
methods, namely "==" and "eql?"
Thank you...

ri Object#eql?

...
The +eql?+ method returns +true+ if _obj_ and _anObject_ have the
same value. Used by +Hash+ to test members for equality. For
objects of class +Object+, +eql?+ is synonymous with +==+.
Subclasses normally continue this tradition, but there are
exceptions. +Numeric+ types, for example, perform type conversion
across +==+, but not across +eql?+, so:
1 == 1.0 #=> true
1.eql? 1.0 #=> false

Greetings,

Esad
 
T

Tomasz Wegrzanowski

Not too long ago, there was a thread about a bug in Ruby where vectors
(which turned out to be derived from matrices) failed to work as hash keys.
The problem turned out to be a typo in the definition of the Matrix class.
The method "eql?" is used by hashes for key comparison but, in the Matrix
class, this method was named "eqn?" by mistake.
This got me thinking about the role of the "eql?" method. Why does it
exist? What is the Ruby rationale behind having two different equality
methods, namely "==" and "eql?"

Most languages provide many equality operators,
as depending on context different kind of "equality" is needed.

Obviously we want 1.0 == 1 to be true, right ?
And as obviously, we want a_hash[1.0] and a_hash[1] to be different.
So we have == and eql?, and even equal? for "is-it-the-same-object".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top