0
0
Rubyprogramming~5 mins

Object identity (equal? vs ==) in Ruby

Choose your learning style9 modes available
Introduction

We use object identity to check if two things are exactly the same object or just look alike. This helps avoid confusion when working with data.

When you want to know if two variables point to the exact same thing in memory.
When comparing two objects that might have the same content but are different objects.
When checking if a method returns the same object or a new copy.
When debugging to understand if changes affect one or both variables.
When optimizing code to avoid unnecessary duplication.
Syntax
Ruby
object1.equal?(object2)
object1 == object2

equal? checks if both variables point to the exact same object.

== checks if the content or value of two objects is the same.

Examples
Both a and b point to the same string object, so equal? is true.
Ruby
a = "hello"
b = a
puts a.equal?(b)  # true
puts a == b        # true
a and b have the same content but are different objects, so equal? is false but == is true.
Ruby
a = "hello"
b = "hello"
puts a.equal?(b)  # false
puts a == b       # true
For small numbers, Ruby may reuse the same object, so equal? can be true. But == always checks value equality.
Ruby
a = 100
b = 100
puts a.equal?(b)  # true or false depends on Ruby version
puts a == b       # true
Sample Program

This program shows the difference between equal? and == with strings. a and b are the same object, but c is a different object with the same content.

Ruby
a = "cat"
b = a
c = "cat"

puts "a.equal?(b): #{a.equal?(b)}"
puts "a == b: #{a == b}"

puts "a.equal?(c): #{a.equal?(c)}"
puts "a == c: #{a == c}"
OutputSuccess
Important Notes

Use equal? when you want to check if two variables are exactly the same object.

Use == when you want to check if two objects have the same value or content.

Remember that some objects like numbers or symbols may behave differently with equal? because Ruby can reuse them.

Summary

equal? checks if two variables point to the same object.

== checks if two objects have the same content.

Knowing the difference helps avoid bugs and understand how Ruby handles objects.