Bird
0
0

Given an array items of hashes with keys :title and :rating, how do you sort items first by descending :rating and then by ascending :title using sort_by?

hard📝 Application Q8 of 15
Ruby - Enumerable and Collection Processing
Given an array items of hashes with keys :title and :rating, how do you sort items first by descending :rating and then by ascending :title using sort_by?
Aitems.sort_by { |item| [item[:title], -item[:rating]] }
Bitems.sort_by { |item| [item[:rating], item[:title]] }
Citems.sort_by { |item| [-item[:rating], item[:title]] }
Ditems.sort_by { |item| [-item[:title], item[:rating]] }
Step-by-Step Solution
Solution:
  1. Step 1: Sort by multiple criteria

    Use an array of keys in sort_by to sort by multiple fields.
  2. Step 2: Descending rating

    Negate rating to sort descending: -item[:rating].
  3. Step 3: Ascending title

    Use title as is for ascending alphabetical order.
  4. Final Answer:

    items.sort_by { |item| [-item[:rating], item[:title]] } -> Option C
  5. Quick Check:

    Negate numeric keys for descending in sort_by [OK]
Quick Trick: Negate numeric keys for descending sort in sort_by [OK]
Common Mistakes:
  • Not negating rating for descending order
  • Swapping order of keys incorrectly
  • Negating string keys which causes errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes