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 = [10, 20, 30, 40, 50]
puts arr[2]
puts arr.first
puts arr[-2]
A40 10 30
B30 10 40
C30 50 40
D20 10 50
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate arr[2]

    Index 2 is the third element, which is 30.
  2. Step 2: Evaluate arr.first and arr[-2]

    arr.first is 10 (first element), arr[-2] is second last element, 40.
  3. Final Answer:

    30 10 40 -> Option B
  4. Quick Check:

    Index 2 = 30, first = 10, second last = 40 [OK]
Quick Trick: Remember index starts at 0; negative counts from end [OK]
Common Mistakes:
  • Confusing index 2 with index 3
  • Mixing up first and last elements
  • Misunderstanding negative indexes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes