Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Methods
What will be the output of the following Ruby code?
arr = [1, 2, 3]
arr.reverse
puts arr.inspect
arr.reverse!
puts arr.inspect
A[1, 2, 3]\n[3, 2, 1]
B[3, 2, 1]\n[1, 2, 3]
C[1, 2, 3]\n[1, 2, 3]
D[3, 2, 1]\n[3, 2, 1]
Step-by-Step Solution
Solution:
  1. Step 1: Understand arr.reverse effect

    arr.reverse returns a new reversed array but does not change arr itself, so arr.inspect prints the original: [1, 2, 3].
  2. Step 2: Understand arr.reverse! effect

    arr.reverse! reverses arr in place, changing it to [3, 2, 1]. So the second print shows [3, 2, 1].
  3. Final Answer:

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

    Non-bang no change, bang changes object [OK]
Quick Trick: Non-bang returns new object; bang changes original [OK]
Common Mistakes:
  • Assuming reverse changes original array
  • Confusing output order
  • Ignoring bang method effect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes