krahets/hello-algo · error · IndexError
索引越界
Error message
索引越界
What it means
Ruby IndexError raised by MyList#get. The guard `raise IndexError, "索引越界" if index < 0 || index >= size` rejects negative indices (which Ruby's Array would otherwise wrap) and indices at/above the live element count. The custom List enforces strict bounds because its backing Array is sized to @capacity, not @size, so unchecked reads could return nil-filled capacity slots.
Source
Thrown at codes/ruby/chapter_array_and_linkedlist/my_list.rb:23
=end
### 列表类 ###
class MyList
attr_reader :size # 获取列表长度(当前元素数量)
attr_reader :capacity # 获取列表容量
### 构造方法 ###
def initialize
@capacity = 10
@size = 0
@extend_ratio = 2
@arr = Array.new(capacity)
end
### 访问元素 ###
def get(index)
# 索引如果越界,则抛出异常,下同
raise IndexError, "索引越界" if index < 0 || index >= size
@arr[index]
end
### 访问元素 ###
def set(index, num)
raise IndexError, "索引越界" if index < 0 || index >= size
@arr[index] = num
end
### 在尾部添加元素 ###
def add(num)
# 元素数量超出容量时,触发扩容机制
extend_capacity if size == capacity
@arr[size] = num
# 更新元素数量
@size += 1
endView on GitHub (pinned to 69932aed18)
Solutions
- Validate `index >= 0 && index < list.size` before get(); never bound loops on capacity.
- For negative-index semantics, translate `index += list.size` first and re-check the range.
- Recompute indices after any mutating operation.
Example fix
# before v = list.get(i) # after raise ArgumentError if i < 0 || i >= list.size v = list.get(i)
Defensive patterns
Strategy: validation
Validate before calling
# call BEFORE get(index) raise ArgumentError, "bad index" if index < 0 || index >= list.size v = list.get(index)
Try / catch
begin v = list.get(i) rescue IndexError => e v = nil # or log and skip end
Prevention
- Bound indices on `size`, never on `capacity`.
- Translate negative indices manually (`index += size`) if you need Array-style wrap, then re-validate.
- Recompute indices after every mutating operation.
When it happens
Trigger: Call list.get(i) with i < 0 (Ruby normally allows negative indexing, but this List forbids it), or i >= @size (pointing into the unused capacity tail, or past the last live element). Also after remove() decremented @size while a stale index is reused.
Common situations: Passing -1 expecting the last element (Array semantics) and hitting the negative-index rejection; loops bounded by @capacity instead of size; reusing an index captured before a remove()/clear(); off-by-one `i <= size`.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/8f97340d62812744.
Report an issue: GitHub.