Bird
0
0

What will be printed by this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Enumerable and Collection Processing
What will be printed by this Ruby code?
data = [{score: 10}, {score: 5}, {score: 20}]
sorted = data.sort_by { |d| -d[:score] }
puts sorted.map { |d| d[:score] }.join(", ")
A20, 10, 5
B10, 5, 20
C5, 10, 20
D20, 5, 10
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting by negative score

    Using -d[:score] sorts descending by score.
  2. Step 2: Order scores descending

    Scores sorted: 20, 10, 5.
  3. Final Answer:

    20, 10, 5 -> Option A
  4. Quick Check:

    Negative key sorts descending = 20, 10, 5 [OK]
Quick Trick: Use negative values in sort_by block for descending order [OK]
Common Mistakes:
  • Forgetting negative sign
  • Expecting ascending order
  • Mixing up map and sort_by

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes