How to Use the Ruby equal? Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby equal? method.

Using the equal? method

The equal? method is a built-in method in Ruby that is used to check if two objects refer to the same object in memory.

Syntax

object1.equal?(object2)

This method returns true if object1 and object2 refer to the same object in memory, otherwise it returns false.

Examples

a = "hello"
b = a
c = "hello"

puts a.equal?(b)  # true
puts a.equal?(c)  # false

In the above example, a and b refer to the same object in memory because they both have the value “hello”. On the other hand, c has a different object id even though it has the same value as a.

It is important to note that the equal? method should not be used to compare the values of two objects. Instead, use the == or eql? methods for value comparison.

a = "hello"
b = "hello"

puts a == b    # true
puts a.eql?(b) # true
puts a.equal?(b) # false

In the above example, a and b have the same value but are not the same object in memory. The == and eql? methods return true because they compare the values of the objects, whereas the equal? method returns false because the objects have different object ids.