Bird
0
0

You want to sort an array of numbers in ascending order using the spaceship operator. Which code snippet correctly uses inside the sort method?

hard📝 Application Q8 of 15
Ruby - Operators and Expressions
You want to sort an array of numbers in ascending order using the spaceship operator. Which code snippet correctly uses <=> inside the sort method?
Aarr.sort { a, b => a <=> b }
Barr.sort { |a, b| b <=> a }
Carr.sort { |a, b| a <=> b }
Darr.sort { |a| a <=> a }
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting with spaceship operator

    The block for sort takes two parameters and compares them with <=>.
  2. Step 2: Check each option

    arr.sort { |a, b| a <=> b } correctly uses two block parameters and compares a <=> b for ascending order.
  3. Final Answer:

    arr.sort { |a, b| a <=> b } -> Option C
  4. Quick Check:

    Correct block syntax and comparison = D [OK]
Quick Trick: Use two block params and a <=> b for ascending sort [OK]
Common Mistakes:
  • Reversing operands for ascending
  • Using wrong block syntax
  • Using one parameter only

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes