Bird
0
0

Which of the following is the correct syntax to sort an array arr in descending order in Ruby?

easy📝 Syntax Q3 of 15
Ruby - Arrays
Which of the following is the correct syntax to sort an array arr in descending order in Ruby?
Aarr.sort.reverse
Barr.reverse.sort
Carr.sort! { |a, b| a <=> b }
Darr.sort { |a, b| b <=> a }
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting with custom block

    To sort descending, use sort with a block comparing b <=> a.
  2. Step 2: Check each option

    arr.sort.reverse sorts ascending then reverses, which works but is less efficient. arr.sort { |a, b| b <=> a } directly sorts descending using block.
  3. Final Answer:

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

    Descending sort uses sort with block b <=> a [OK]
Quick Trick: Use sort { |a,b| b <=> a } for descending sort [OK]
Common Mistakes:
  • Using reverse.sort instead of sort.reverse
  • Using sort! without block for descending
  • Confusing block order in sort

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes