Bird
0
0

Identify the problem in this Ruby code:

medium📝 Debug Q7 of 15
Ruby - Arrays
Identify the problem in this Ruby code:
arr = [1, 2, 3]
puts arr[3]
ASyntax error due to missing parentheses
BIndex 3 is out of range and returns nil
Carr[3] returns 3
DArray indices start at 1, so arr[3] is valid
Step-by-Step Solution
Solution:
  1. Step 1: Understand array indexing in Ruby

    Ruby arrays start at index 0, so arr[3] is the fourth element, which does not exist.
  2. Step 2: Check what happens when accessing out-of-range index

    Accessing arr[3] returns nil, no error occurs.
  3. Final Answer:

    Index 3 is out of range and returns nil -> Option B
  4. Quick Check:

    Out-of-range index returns nil [OK]
Quick Trick: Array indices start at 0; out-of-range returns nil [OK]
Common Mistakes:
MISTAKES
  • Expecting error on out-of-range
  • Thinking indices start at 1
  • Assuming arr[3] returns 3

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes