Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Arrays
What will be the output of this Ruby code?
arr = [3, 7, 4, 2]
arr.sort!
arr.reverse!
p arr
A[2, 3, 4, 7]
B[7, 4, 3, 2]
C[3, 7, 4, 2]
D[2, 4, 3, 7]
Step-by-Step Solution
Solution:
  1. Step 1: Sort the array in place

    arr.sort! changes arr to [2, 3, 4, 7].
  2. Step 2: Reverse the array in place

    arr.reverse! changes arr to [7, 4, 3, 2].
  3. Final Answer:

    [7, 4, 3, 2] -> Option B
  4. Quick Check:

    sort! then reverse! modifies original array [OK]
Quick Trick: sort! and reverse! change original array [OK]
Common Mistakes:
  • Expecting sorted ascending output
  • Using non-bang methods expecting in-place change
  • Confusing order of operations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes