Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Arrays
What is the output of the following Ruby code?
arr = ['a', 'b', 'c', 'd']
puts arr[-1]
puts arr[-3]
Aa c
Bd b
Cd c
DError
Eb d
Step-by-Step Solution
Solution:
  1. Step 1: Understand negative indexing in Ruby arrays

    Negative indexes count from the end: -1 is last element, -2 is second last, etc.
  2. Step 2: Identify elements at arr[-1] and arr[-3]

    arr[-1] is 'd' (last element), arr[-3] is 'b' (third from last).
  3. Final Answer:

    d b -> Option B
  4. Quick Check:

    Negative index -1 = last element [OK]
Quick Trick: Negative index -1 means last element in Ruby arrays [OK]
Common Mistakes:
  • Confusing negative indexes with positive
  • Expecting arr[-1] to be first element
  • Thinking negative indexes cause errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes