Here’s a note on how to remember eql?
and equal?
, which frequently appear in the Ruby Silver exam.
These types of questions are commonly asked in the exam:
What will be displayed when the following code is executed?
a = "abc"
b = "abc"
print a.eql? b
print a.equal? b
print a == b
truefalsetrue
The textbook explanation is as follows:
The
eql?
method is used internally in hashes to check if keys are the same. It checks if the receiverobj
is the same as the argumentother_obj
, returningtrue
if they are the same andfalse
otherwise. To compare objects, typically you don’t use theeql?
method. Use the==
method to check if the “contents of the objects are the same” and theequal?
method to check if they are “the same object.” Theeql?
method in theObject
class only checks if they are the same object, which is the same as theequal?
method. However, in classes likeString
andArray
, theeql?
method is overridden to check if “contents are the same.” Reference: Ruby Documentation
However, this explanation can sometimes be hard to remember, so I use the following mnemonic:
eql?
checks if they are “approximately equal,” so it’s shorter.equal?
checks more thoroughly, so it’s longer.