Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
people = [{name: "Anna", age: 30}, {name: "Bob", age: 25}, {name: "Cara", age: 35}]
sorted = people.sort_by { |person| person[:age] }
puts sorted.map { |p| p[:name] }
A["Anna", "Bob", "Cara"]
B["Bob", "Anna", "Cara"]
C["Cara", "Anna", "Bob"]
D["Bob", "Cara", "Anna"]
Step-by-Step Solution
Solution:
  1. Step 1: Understand sorting by age

    The array is sorted by the :age key in ascending order: 25, 30, 35.
  2. Step 2: Map sorted array to names

    After sorting, the order is Bob (25), Anna (30), Cara (35). Mapping names gives ["Bob", "Anna", "Cara"].
  3. Final Answer:

    ["Bob", "Anna", "Cara"] -> Option B
  4. Quick Check:

    sort_by age ascending = [Bob, Anna, Cara] [OK]
Quick Trick: Sort_by returns new array sorted by block value [OK]
Common Mistakes:
  • Assuming sort_by sorts descending by default
  • Confusing keys in hash access
  • Not mapping to names after sorting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes