krahets/hello-algo · error · IndexError
栈为空
Error message
栈为空
What it means
Raised by `ArrayStack#pop` (array_stack.rb:31) when `is_empty?` is true. The stack delegates storage to Ruby's `Array#pop`; the guard exists to throw a descriptive IndexError rather than letting `Array#pop` silently return nil. It enforces the stack ADT contract that pop on an empty container is an error.
Source
Thrown at codes/ruby/chapter_stack_and_queue/array_stack.rb:31
### 获取栈的长度 ###
def size
@stack.length
end
### 判断栈是否为空 ###
def is_empty?
@stack.empty?
end
### 入栈 ###
def push(item)
@stack << item
end
### 出栈 ###
def pop
raise IndexError, '栈为空' if is_empty?
@stack.pop
end
### 访问栈顶元素 ###
def peek
raise IndexError, '栈为空' if is_empty?
@stack.last
end
### 返回列表用于打印 ###
def to_array
@stack
end
end
### Driver Code ###View on GitHub (pinned to 69932aed18)
Solutions
- Check `stack.is_empty?` before calling `pop`.
- Track push/pop balance with a counter in the caller.
- Rescue IndexError if an empty pop is a recoverable condition.
Example fix
# before val = stack.pop # after val = stack.is_empty? ? nil : stack.pop
Defensive patterns
Strategy: validation
Validate before calling
return nil if stack.is_empty? stack.pop
Type guard
def stack_popable?(stack) stack.respond_to?(:is_empty?) && stack.respond_to?(:pop) && !stack.is_empty? end
Try / catch
begin stack.pop rescue IndexError nil end
Prevention
- Check is_empty? before pop.
- Maintain a push/pop balance invariant in the caller.
- In backtracking, verify depth > 0 before popping.
When it happens
Trigger: Calling `stack.pop` when the backing `@stack` array is empty. Occurs after popping all pushed items, or on a freshly constructed stack.
Common situations: Unbalanced push/pop pairs (more pops than pushes); expression-evaluation or backtracking algorithms that over-pop; test calling pop before any push.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/1e6d7892255b0f89.
Report an issue: GitHub.