Why so many methods of comparison?
equal?
corresponds to instance equality. Is it the same object in memory?==
andeql?
are in most cases aliases. They correspond to the « natural » equality of object values (Exception for Object: alias forequal?
).===
is called « case equality ». It is this method that is called in acase...when
. By default, it is an alias of==
.
The ===
can be seen as a notion of belonging: do you belong to what I represent? ⚠️ This method is generally neither reflexive, symmetrical nor transitive.
The documentation states: « The eql? method returns true if obj and other refer to the same hash key ».
In practice, this often translates into object type equality. In a way, eql?
is the equivalent of Javascript’s ===
(and not Ruby’s ===
!).
⚠️ Counter-examples can be found on some implementations of the eql?
method that don’t respect the definition.
Links to Ruby documentation for ==
, eql?
, equal?
and ===
.