krahets/hello-algo · error · IndexError
Stack is empty
Error message
Stack is empty
What it means
Raised by ArrayStack#pop (en/codes/ruby/chapter_stack_and_queue/array_stack.rb:31) when the underlying @stack array is empty. ArrayStack wraps a Ruby Array; it re-implements the empty guard because the teaching version wants an explicit IndexError with its own message rather than the stdlib nil-return from Array#pop.
Source
Thrown at en/codes/ruby/chapter_stack_and_queue/array_stack.rb:31
### Get stack length ###
def size
@stack.length
end
### Check if stack is empty ###
def is_empty?
@stack.empty?
end
### Push ###
def push(item)
@stack << item
end
### Pop ###
def pop
raise IndexError, 'Stack is empty' if is_empty?
@stack.pop
end
### Access top element ###
def peek
raise IndexError, 'Stack is empty' if is_empty?
@stack.last
end
### Return list for printing ###
def to_array
@stack
end
end
### Driver Code ###View on GitHub (pinned to 69932aed18)
Solutions
- Check stack.is_empty? (or stack.size == 0) before calling pop.
- Ensure every pop in a loop has a matching earlier push; verify counts are balanced.
- Catch IndexError around the pop and return a default (nil or sentinel) when empty is an expected state.
Example fix
# before while true stack.pop # raises once drained end # after stack.pop until stack.is_empty?
Defensive patterns
Strategy: validation
Validate before calling
stack.pop unless stack.is_empty?
Type guard
def stack_nonempty?(s); s.respond_to?(:is_empty?) && !s.is_empty?; end
Try / catch
begin stack.pop rescue IndexError nil # empty stack end
Prevention
- Check is_empty? before every pop.
- Keep push/pop counts balanced in matching/parsing algorithms.
- Push a sentinel frame if your algorithm assumes a non-empty top.
When it happens
Trigger: Calling stack.pop when stack.is_empty? is true — i.e. when @stack has no elements. Occurs after popping as many items as were pushed, or on a brand-new ArrayStack before any push.
Common situations: Unbalanced push/pop counts in a bracket-matching or expression-evaluation exercise; popping in a while loop with is_empty? checked against the wrong variable; reusing a stack across recursive calls that fully drain it.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/24a9c7dc234af232.
Report an issue: GitHub.