0
0
Rubyprogramming~3 mins

Object identity (equal? vs ==) in Ruby - When to Use Which

Choose your learning style9 modes available
The Big Idea

Are your objects truly the same, or just pretending to be?

The Scenario

Imagine you have two boxes that look exactly the same and contain the same toys. You want to check if they are the same box or just two boxes with the same toys.

The Problem

Manually checking if two things are exactly the same object or just look alike is confusing and easy to get wrong. You might think two things are equal because they look the same, but they could be different objects in memory.

The Solution

Ruby gives you two ways to compare: == checks if two objects look equal, while equal? checks if they are the exact same object. This helps you avoid mistakes and understand your program better.

Before vs After
Before
if a == b
  puts 'Looks equal'
end
if a.equal?(b)
  puts 'Same object'
end
After
puts 'Equal in value' if a == b
puts 'Identical object' if a.equal?(b)
What It Enables

This concept lets you clearly tell when two things are just alike or truly the same, helping you write smarter and bug-free code.

Real Life Example

When you copy a list of friends, you want to know if you have a new list with the same names or just another name tag pointing to the original list.

Key Takeaways

== checks if objects look equal.

equal? checks if objects are the exact same.

Knowing the difference helps avoid bugs and confusion.