Bird
0
0

How can you use the spaceship operator to sort an array of strings arr = ['apple', 'banana', 'cherry'] in reverse alphabetical order?

hard📝 Application Q9 of 15
Ruby - Operators and Expressions

How can you use the spaceship operator to sort an array of strings arr = ['apple', 'banana', 'cherry'] in reverse alphabetical order?

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

    To sort descending, compare b to a.
  2. Step 2: Use sort with block

    Use arr.sort { |a, b| b <=> a } to reverse order.
  3. Final Answer:

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

    Reverse order swaps operands [OK]
Quick Trick: Swap operands for descending sort [OK]
Common Mistakes:
  • Using a <=> b for descending order
  • Misusing sort_by with spaceship
  • Trying to reverse after sort with block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes