Bird
0
0

Given the array arr = [3, 1, 4, 1, 5], which code snippet correctly sorts the array in descending order using the spaceship operator?

hard📝 Application Q15 of 15
Ruby - Operators and Expressions

Given the array arr = [3, 1, 4, 1, 5], which code snippet correctly sorts the array in descending order using the spaceship operator?

Aarr.sort { |a, b| b <=> a }
Barr.sort { |a, b| a == b }
Carr.sort_by { |x| x <=> 0 }
Darr.sort { |a, b| a <=> b }
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting with spaceship operator

    The block compares two elements a and b. To sort descending, compare b to a.
  2. Step 2: Analyze each option

    arr.sort { |a, b| a <=> b } sorts ascending (a <=> b).
    arr.sort { |a, b| b <=> a } sorts descending (b <=> a).
    arr.sort_by { |x| x <=> 0 } misuses sort_by with spaceship operator.
    arr.sort { |a, b| a == b } returns boolean, invalid for sorting.
  3. Final Answer:

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

    Reverse order uses b <=> a [OK]
Quick Trick: Reverse order: swap a and b in <=> [OK]
Common Mistakes:
MISTAKES
  • Using a <=> b for descending sort
  • Misusing sort_by with spaceship operator
  • Returning boolean instead of integer in block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes