Bird
0
0

The following Ruby code throws an error. What is the problem?

medium📝 Debug Q14 of 15
Ruby - Arrays
The following Ruby code throws an error. What is the problem?
arr = [5, 10, 15]
puts arr.first()
puts arr[-4]
ANegative index -4 is out of range and returns nil, no error
BMissing argument in first() causes error
CArray is empty, so first() fails
DSyntax error in calling first()
Step-by-Step Solution
Solution:
  1. Step 1: Check arr.first() usage

    first() can be called with or without parentheses; no error here.
  2. Step 2: Analyze arr[-4]

    Array has 3 elements, so index -4 is out of range and returns nil, which prints as empty line, no error.
  3. Final Answer:

    Negative index -4 is out of range and returns nil, no error -> Option A
  4. Quick Check:

    Out of range negative index returns nil [OK]
Quick Trick: Out of range negative index returns nil, no error [OK]
Common Mistakes:
  • Assuming out of range index causes error
  • Thinking first() needs arguments
  • Confusing nil with error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes