krahets/hello-algo · error · IndexError
キューは空です
Error message
キューは空です
What it means
Raised by LinkedListQueue#peek (ja) when `is_empty?` is true. Because `pop` is implemented as `num = peek; @front = @front.next; ...`, the same IndexError surfaces for BOTH `peek` and `pop` on an empty queue — the failure originates at line 55 inside peek. The guard protects against dereferencing the nil @front.
Source
Thrown at ja/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb:55
@rear.next = node
@rear = node
end
@size += 1
end
### デキュー ###
def pop
num = peek
# 先頭ノードを削除
@front = @front.next
@size -= 1
num
end
### 先頭要素にアクセス ###
def peek
raise IndexError, 'キューは空です' if is_empty?
@front.val
end
### 連結リストを Array に変換して返す ###
def to_array
queue = []
temp = @front
while temp
queue << temp.val
temp = temp.next
end
queue
end
end
### Driver Code ###
if __FILE__ == $0View on GitHub (pinned to 69932aed18)
Solutions
- Check `queue.is_empty?` (or `queue.size.zero?`) before calling peek or pop.
- Cap your consumer loop on `queue.size > 0` rather than a fixed count.
- If you need non-raising semantics, wrap pop in a helper that returns nil when empty.
Example fix
// before queue.pop # raises 'キューは空です' when drained // after item = queue.is_empty? ? nil : queue.pop
Defensive patterns
Strategy: validation
Validate before calling
item = queue.pop unless queue.is_empty?
Type guard
def queue_nonempty?(q) = !q.is_empty?
Try / catch
begin item = queue.pop # also covers peek rescue IndexError item = nil end
Prevention
- Remember pop delegates to peek — guard covers both.
- Bound consumer loops with `until queue.is_empty?`.
- For optional dequeue, wrap pop in a helper returning nil.
When it happens
Trigger: Calling `queue.peek` or `queue.pop` on an empty LinkedListQueue. Any dequeue-after-drain, or a consumer that pops in a loop without a size check, will hit this on the first empty operation.
Common situations: A producer/consumer loop where the consumer outpaces the producer; popping the last item then popping once more; a driver block that peeks before enqueueing anything.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/8d09371475c06ca2.
Report an issue: GitHub.