shou2017.com
JP

How to Remember eql? and equal? for the Ruby Exam

Sun May 13, 2018
Sat Aug 10, 2024

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:

From [Revised 2nd Edition] Ruby Certification Exam Study Guide (Silver/Gold) Official Ruby Certification Textbook

Question

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

Answer

  • 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 receiver obj is the same as the argument other_obj, returning true if they are the same and false otherwise. To compare objects, typically you don’t use the eql? method. Use the == method to check if the “contents of the objects are the same” and the equal? method to check if they are “the same object.” The eql? method in the Object class only checks if they are the same object, which is the same as the equal? method. However, in classes like String and Array, the eql? 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.
See Also