Bird
0
0

Given an array of strings words = ["pear", "apple", "banana"], how can you sort it by string length in descending order?

hard📝 Application Q8 of 15
Ruby - Arrays
Given an array of strings words = ["pear", "apple", "banana"], how can you sort it by string length in descending order?
AAll of the above
Bwords.sort { |a, b| b.length <=> a.length }
Cwords.sort_by(&:length).reverse!
Dwords.sort_by(&:length).reverse
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting by length descending

    Sorting by length descending can be done by sorting with a block comparing lengths or sorting by length then reversing.
  2. Step 2: Check each option

    words.sort { |a, b| b.length <=> a.length } sorts with block comparing lengths descending. words.sort_by(&:length).reverse sorts by length ascending then reverses. words.sort_by(&:length).reverse! does the same but reverses in place. All produce correct descending order.
  3. Final Answer:

    All of the above -> Option A
  4. Quick Check:

    Multiple ways to sort descending by length [OK]
Quick Trick: Use sort with block or sort_by + reverse for custom sorting [OK]
Common Mistakes:
MISTAKES
  • Forgetting to reverse after sort_by
  • Using sort without block for length
  • Confusing reverse and reverse!

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes