Quick Answer
Handle array boundary errors.
Understanding the Issue
Occurs when accessing array elements beyond valid indices.
The Problem
This code demonstrates the issue:
Ruby
Error
arr = [1, 2, 3]
arr[5] # Returns nil
arr.fetch(5) # IndexError
The Solution
Here's the corrected code:
Ruby
Fixed
# Solution 1: Check array length
index = 5
if index < arr.length
arr[index]
end
# Solution 2: Use fetch with fallback
arr.fetch(5, "default")
# Solution 3: Safe navigation
arr.at(5)&.some_method
# Solution 4: Handle negative indices
arr[-1] # Last element
arr[-arr.length] # First element
Key Takeaways
Always validate array indices before access.