Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Arrays
What is the output of the following Ruby code?
arr = [3, 1, 4, 2]
sorted_arr = arr.sort
reversed_arr = sorted_arr.reverse
puts reversed_arr.inspect
A[1, 2, 3, 4]
B[3, 1, 4, 2]
C[4, 3, 2, 1]
D[2, 4, 1, 3]
Step-by-Step Solution
Solution:
  1. Step 1: Sort the original array

    Calling arr.sort returns a new array sorted ascending: [1, 2, 3, 4].
  2. Step 2: Reverse the sorted array

    Calling sorted_arr.reverse flips the order to [4, 3, 2, 1].
  3. Final Answer:

    [4, 3, 2, 1] -> Option C
  4. Quick Check:

    sort then reverse = descending order [OK]
Quick Trick: Sort then reverse = descending order [OK]
Common Mistakes:
  • Assuming reverse modifies original array
  • Confusing sorted array with original
  • Expecting reverse to sort ascending

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes