0
0
Rubyprogramming~10 mins

Object identity (equal? vs ==) in Ruby - Visual Side-by-Side Comparison

Choose your learning style9 modes available
Concept Flow - Object identity (equal? vs ==)
Create obj1
Create obj2
Compare obj1 == obj2?
Compare obj1.equal?(obj2)?
This flow shows creating two objects and comparing them using == and equal? to check value equality vs object identity.
Execution Sample
Ruby
obj1 = "hello"
obj2 = "hello"
puts obj1 == obj2
puts obj1.equal?(obj2)
Creates two string objects with same content, compares with == and equal? to show difference.
Execution Table
StepActionobj1obj2obj1 == obj2obj1.equal?(obj2)Output
1Create obj1 = "hello""hello" (obj1)----
2Create obj2 = "hello""hello" (obj1)"hello" (obj2)---
3Compare obj1 == obj2"hello" (obj1)"hello" (obj2)true-true
4Compare obj1.equal?(obj2)"hello" (obj1)"hello" (obj2)-falsefalse
5End"hello" (obj1)"hello" (obj2)truefalse-
💡 Comparison ends after checking both == and equal? methods.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
obj1nil"hello" (obj1)"hello" (obj1)"hello" (obj1)
obj2nilnil"hello" (obj2)"hello" (obj2)
Key Moments - 2 Insights
Why does obj1 == obj2 return true but obj1.equal?(obj2) return false?
Because == checks if the content or value is the same (see step 3), while equal? checks if both variables point to the exact same object in memory (step 4). Here, obj1 and obj2 have same content but are different objects.
Can two different objects have the same value in Ruby?
Yes, as shown in step 2 and 3, obj1 and obj2 are different objects but have identical string content, so == returns true but equal? returns false.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3, what does obj1 == obj2 evaluate to?
Atrue
Bfalse
Cnil
Derror
💡 Hint
Check the 'obj1 == obj2' column in row for step 3 in execution_table.
At which step does obj1.equal?(obj2) get evaluated?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column in execution_table to find when equal? is called.
If obj2 was assigned as obj2 = obj1, what would obj1.equal?(obj2) return?
Anil
Bfalse
Ctrue
Derror
💡 Hint
Refer to variable_tracker to see that both variables point to the same object if assigned directly.
Concept Snapshot
In Ruby:
- == checks if two objects have the same value/content.
- equal? checks if two variables point to the exact same object.
- Different objects can be == true but equal? false.
- Use equal? to test object identity, == for value equality.
Full Transcript
This example creates two string objects obj1 and obj2 with the same content "hello". When comparing with ==, Ruby checks if their values are equal, which is true. But equal? checks if both variables point to the same object in memory, which is false here because they are separate objects. This shows the difference between value equality and object identity in Ruby.