krahets/hello-algo · error · IndexError
堆疊為空
Error message
堆疊為空
What it means
Raised by the pop method of the ArrayStack teaching class (backed by Ruby's Array) when is_empty? is true. Although Ruby's own Array.pop returns nil on empty, this teaching implementation explicitly raises IndexError to demonstrate proper stack-underflow handling. The guard fires before delegating to @stack.pop.
Source
Thrown at zh-hant/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.
- Use while !stack.is_empty? to drain the stack safely.
- Return nil when empty: stack.is_empty? ? nil : stack.pop.
- Be aware this is stricter than Ruby's native Array.pop — do not assume nil-return semantics.
Example fix
# before
3.times { val = stack.pop } # raises if stack has fewer than 3 elements
# after
until stack.is_empty?
val = stack.pop
end Defensive patterns
Strategy: validation
Validate before calling
return nil if stack.is_empty? stack.pop
Type guard
# Ruby: safe pop def safe_pop(stack) stack.is_empty? ? nil : stack.pop end
Try / catch
begin val = stack.pop rescue IndexError val = nil # stack underflow end
Prevention
- Do not assume nil-return semantics like Ruby's native Array.pop — this raises.
- Use 'until stack.is_empty?' to drain.
- Track push/pop counts to catch underflow early.
When it happens
Trigger: Calling stack.pop on a newly constructed stack, calling pop more times than elements were pushed, or popping in a drain loop without an emptiness check.
Common situations: Assuming the stack has elements when it does not; mismatched push/pop counts; treating this stack like a raw Ruby Array (which silently returns nil on empty pop).
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/9ddc6e6fd44d1d33.
Report an issue: GitHub.