Bird
0
0

Why does the spaceship operator return nil when comparing some objects in Ruby?

hard📝 Conceptual Q10 of 15
Ruby - Operators and Expressions
Why does the spaceship operator return nil when comparing some objects in Ruby?
ABecause the objects are the same instance
BBecause the objects are equal
CBecause the operator is used incorrectly
DBecause the objects are not comparable
Step-by-Step Solution
Solution:
  1. Step 1: Understand spaceship operator behavior with incomparable objects

    If objects cannot be compared, the operator returns nil.
  2. Step 2: Confirm this is due to lack of comparison method

    Objects without a defined comparison method cause <=> to return nil.
  3. Final Answer:

    Because the objects are not comparable -> Option D
  4. Quick Check:

    Incomparable objects cause nil result [OK]
Quick Trick: Spaceship returns nil if objects can't be compared [OK]
Common Mistakes:
MISTAKES
  • Thinking nil means equality
  • Assuming operator misuse
  • Confusing instance identity with comparability

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes