Bird
0
0

What is the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Arrays
What is the output of this Ruby code?
arr = [5, 2, 9, 1]
sorted = arr.sort.reverse
p sorted
A[1, 2, 5, 9]
B[9, 5, 2, 1]
C[5, 2, 9, 1]
D[1, 5, 2, 9]
Step-by-Step Solution
Solution:
  1. Step 1: Sort the array in ascending order

    arr.sort returns [1, 2, 5, 9].
  2. Step 2: Reverse the sorted array

    Reversing [1, 2, 5, 9] gives [9, 5, 2, 1].
  3. Final Answer:

    [9, 5, 2, 1] -> Option B
  4. Quick Check:

    sort then reverse = descending array [OK]
Quick Trick: sort then reverse gives descending order [OK]
Common Mistakes:
  • Expecting original array output
  • Confusing reverse before sort
  • Misreading sort order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes