0
0
Rubyprogramming~15 mins

Object identity (equal? vs ==) in Ruby - Hands-On Comparison

Choose your learning style9 modes available
Understanding Object Identity with equal? vs ==
📖 Scenario: Imagine you have two boxes that look the same and hold the same toys. You want to check if they are actually the same box or just two boxes with the same toys inside.
🎯 Goal: You will learn how to check if two objects are exactly the same object in memory or just look equal in Ruby using equal? and ==.
📋 What You'll Learn
Create two string variables with the same content
Create a third variable pointing to one of the first strings
Use equal? to check if two variables point to the same object
Use == to check if two variables have the same content
Print the results clearly
💡 Why This Matters
🌍 Real World
Understanding object identity helps avoid bugs when working with data that might look the same but are different objects, such as user inputs or data from files.
💼 Career
Many programming jobs require knowing when two variables refer to the same object or just equal data, especially in debugging and optimizing code.
Progress0 / 4 steps
1
Create two string variables with the same content
Create two string variables called string1 and string2 with the exact value "hello".
Ruby
Need a hint?

Use = to assign the string "hello" to both string1 and string2.

2
Create a third variable pointing to the first string
Create a variable called string3 and set it equal to string1.
Ruby
Need a hint?

Assign string3 to be the same object as string1 by using =.

3
Check object identity with equal?
Use equal? to check if string1 and string2 are the same object, and also if string1 and string3 are the same object. Store the results in variables same_object_1_2 and same_object_1_3 respectively.
Ruby
Need a hint?

Use variable = object1.equal?(object2) to check if two variables point to the same object.

4
Print the results of equal? and ==
Print the values of same_object_1_2 and same_object_1_3. Then print the result of string1 == string2 and string1 == string3 to show if their contents are equal.
Ruby
Need a hint?

Use puts with string interpolation to print the variable names and their values clearly.