Bird
0
0

You want to check if two variables x and y refer to the same object, but x might be nil. Which Ruby code safely performs this check without errors?

hard📝 Application Q15 of 15
Ruby - Classes and Objects
You want to check if two variables x and y refer to the same object, but x might be nil. Which Ruby code safely performs this check without errors?
Ax.equal?(y)
By.equals(x)
Cx&.equal?(y)
Dx == y
Step-by-Step Solution
Solution:
  1. Step 1: Check safety of equal? on nil

    In Ruby, nil is an object and responds to equal?, so x.equal?(y) is safe even if x is nil. It returns false unless y is also nil.
  2. Step 2: Eliminate distractors

    x&.equal?(y) returns nil if x is nil, which is not a proper boolean result. y.equals(x) calls a non-existent method. x == y checks content, not identity.
  3. Final Answer:

    x.equal?(y) -> Option A
  4. Quick Check:

    nil.equal?(y) safe boolean check = C [OK]
Quick Trick: Even nil.equal?(other) works without error [OK]
Common Mistakes:
  • Using &. which returns nil instead of boolean
  • Calling non-existent equals method
  • Using == which checks content, not identity

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes