Bird
0
0

Find the error in this Ruby code snippet:

medium📝 Debug Q7 of 15
Ruby - Arrays
Find the error in this Ruby code snippet:
arr = [10, 20, 30, 40]
slice = arr[1..5]
puts slice.inspect
AIndex 5 is out of bounds but Ruby returns elements up to the last index
BCode raises an IndexError due to out of range index
CThe slice returns nil
DThe code returns an empty array
Step-by-Step Solution
Solution:
  1. Step 1: Check the range 1..5 against array size

    The array has indices 0 to 3; index 5 is out of bounds.
  2. Step 2: Understand Ruby's behavior for out-of-range slicing

    Ruby returns elements from index 1 up to the last element without error.
  3. Final Answer:

    Index 5 is out of bounds but Ruby returns elements up to the last index -> Option A
  4. Quick Check:

    Ruby slices safely even if end index is too large [OK]
Quick Trick: Ruby slices safely even if end index exceeds array length [OK]
Common Mistakes:
  • Expecting IndexError for out-of-range index
  • Expecting nil or empty array
  • Confusing Ruby with other languages' behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes