0
0
Rubyprogramming~20 mins

Object identity (equal? vs ==) in Ruby - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Object Identity Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Understanding == vs equal? with strings
What is the output of this Ruby code?
Ruby
a = "hello"
b = "hello"
puts a == b
puts a.equal?(b)
A
false
true
B
true
false
C
true
true
D
false
false
Attempts:
2 left
💡 Hint
Remember that == checks value equality, while equal? checks if both variables point to the same object.
Predict Output
intermediate
2:00remaining
Object identity with integers
What will this Ruby code print?
Ruby
x = 1000
y = 1000
puts x == y
puts x.equal?(y)
A
true
false
B
true
true
C
false
false
D
false
true
Attempts:
2 left
💡 Hint
Check how Ruby handles integers and object identity for large numbers.
Predict Output
advanced
2:00remaining
Comparing symbols with == and equal?
What is the output of this Ruby code?
Ruby
sym1 = :ruby
sym2 = :ruby
puts sym1 == sym2
puts sym1.equal?(sym2)
A
true
false
B
false
false
C
false
true
D
true
true
Attempts:
2 left
💡 Hint
Symbols are unique and immutable in Ruby.
Predict Output
advanced
2:00remaining
Effect of dup on object identity
What does this Ruby code print?
Ruby
arr1 = [1, 2, 3]
arr2 = arr1.dup
puts arr1 == arr2
puts arr1.equal?(arr2)
A
true
false
B
true
true
C
false
false
D
false
true
Attempts:
2 left
💡 Hint
dup creates a shallow copy of the object.
Predict Output
expert
2:00remaining
Mutable objects and identity after modification
What is the output of this Ruby code?
Ruby
str1 = "hello"
str2 = str1
str2 << " world"
puts str1
puts str2
puts str1.equal?(str2)
A
hello
hello
true
B
hello
hello world
false
C
hello world
hello world
true
D
hello world
hello world
false
Attempts:
2 left
💡 Hint
Remember that modifying str2 affects str1 if they reference the same object.