krahets/hello-algo · error · IndexError
スタックは空です
Error message
スタックは空です
What it means
Raised by ArrayStack#pop (ja/codes/ruby/chapter_stack_and_queue/array_stack.rb:31) when the stack is empty. It calls @stack.pop; the guard rejects the operation with an explicit message rather than returning nil as stdlib Array#pop would. Message: "スタックは空です" (Stack is empty). Japanese mirror of error 541.
Source
Thrown at ja/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 pop.
- Balance push and pop counts; assert before unwinding.
- Rescue IndexError and return a default when empty is a valid 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 end
Prevention
- Check is_empty? before pop.
- Keep push/pop balanced in parsing/DFS routines.
- Return a default when empty is a valid state.
When it happens
Trigger: Calling stack.pop when stack.is_empty? is true — after popping as many items as pushed, or before the first push.
Common situations: Unbalanced push/pop in an expression-evaluation or DFS routine; popping in a loop with the emptiness check against the wrong variable; reusing a stack across recursive calls that drain it.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/a660e2373a840f2d.
Report an issue: GitHub.