IndexError
RubyERRORNotableCollection
Index out of range or invalid
Quick Answer
Use Array#[] for nil-safe access or Array#fetch with a default block to handle missing indices explicitly.
What this means
Raised when an index is invalid for a collection. It is the parent of KeyError and StopIteration. Array#fetch raises IndexError for out-of-bounds indices, unlike [] which returns nil.
Why it happens
- 1Calling Array#fetch with an index that does not exist
- 2Using a negative index beyond the start of the array
Fix
Use fetch with a default
Use fetch with a default
arr = [1, 2, 3]
value = arr.fetch(10, 'default') # => "default"
# or
value = arr.fetch(10) { |i| "index #{i} not found" }Why this works
fetch with a default value or block returns a fallback instead of raising IndexError.
Code examples
Array#fetch out of boundsruby
[1, 2, 3].fetch(5) # IndexError: index 5 outside of array bounds: -3...3
Array#[] returns nil safelyruby
[1, 2, 3][5] # => nil (no error)
Rescue IndexErrorruby
begin val = arr.fetch(idx) rescue IndexError => e val = nil puts e.message end
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev