Bird
0
0

Consider this Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - Classes and Objects
Consider this Ruby code snippet:
arr1 = [1, 2, 3]
arr2 = arr1
arr3 = [1, 2, 3]

puts arr1.equal?(arr2)
puts arr1.equal?(arr3)
What is the output and why?
Afalse false
Bfalse true
Ctrue true
Dtrue false
Step-by-Step Solution
Solution:
  1. Step 1: Analyze arr1.equal?(arr2)

    Since arr2 is assigned directly from arr1, both point to the same object, so equal? returns true.
  2. Step 2: Analyze arr1.equal?(arr3)

    arr3 is a new array with the same content but a different object, so equal? returns false.
  3. Final Answer:

    true false -> Option D
  4. Quick Check:

    Same object = true, same content but different object = false [OK]
Quick Trick: Assignment copies object reference; new array creates new object [OK]
Common Mistakes:
  • Assuming arrays with same content are the same object
  • Confusing == with equal?
  • Thinking assignment creates a new object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes