Bird
0
0

Identify the error in the following Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - Arrays
Identify the error in the following Ruby code snippet:
arr = [1, 2, 3, 4, 5]
slice = arr[2..6]
puts slice.inspect
ASyntax error due to invalid range
BRange end index 6 is out of bounds but Ruby returns elements up to the end of the array
CRuntime error because index 6 does not exist
Dslice will be empty array because range is invalid
Step-by-Step Solution
Solution:
  1. Step 1: Check the range indexes against array size

    The array has indexes 0 to 4. The range 2..6 goes beyond the last index.
  2. Step 2: Understand Ruby slicing behavior for out-of-bounds

    Ruby returns elements from index 2 to the end (indexes 2, 3, 4) and ignores indexes beyond 4 without error.
  3. Final Answer:

    Range end index 6 is out of bounds but Ruby returns elements up to the end of the array -> Option B
  4. Quick Check:

    Ruby slices safely even if range exceeds array size [OK]
Quick Trick: Ruby slicing ignores out-of-bound indexes without error [OK]
Common Mistakes:
MISTAKES
  • Expecting runtime or syntax error
  • Assuming slice will be empty
  • Confusing Ruby with other languages that error here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes