krahets/hello-algo · error · IndexError

队列为空

Error message

队列为空

What it means

Raised by `ArrayQueue#peek` (array_queue.rb:52) when `is_empty?` is true. `peek` returns `@nums[@front]` to expose the head without dequeueing; on an empty queue `@front` points at a stale slot and the read is meaningless. The `pop` method delegates to `peek`, so an empty dequeue also surfaces here.

Source

Thrown at codes/ruby/chapter_stack_and_queue/array_queue.rb:52

    # 通过取余操作实现 rear 越过数组尾部后回到头部
    rear = (@front + size) % capacity
    # 将 num 添加至队尾
    @nums[rear] = num
    @size += 1
  end

  ### 出队 ###
  def pop
    num = peek
    # 队首指针向后移动一位,若越过尾部,则返回到数组头部
    @front = (@front + 1) % capacity
    @size -= 1
    num
  end

  ### 访问队首元素 ###
  def peek
    raise IndexError, '队列为空' if is_empty?

    @nums[@front]
  end

  ### 返回列表用于打印 ###
  def to_array
    res = Array.new(size, 0)
    j = @front

    for i in 0...size
      res[i] = @nums[j % capacity]
      j += 1
    end

    res
  end
end

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with `unless queue.is_empty?` before `peek` or `pop`.
  2. Drive the consume loop with `while queue.size > 0`.
  3. Rescue IndexError at the call site if empty is a normal sentinel.

Example fix

# before
head = queue.peek

# after
head = queue.is_empty? ? nil : queue.peek
Defensive patterns

Strategy: validation

Validate before calling

return nil if queue.is_empty?
queue.peek

Type guard

def queue_readable?(queue)
  queue.respond_to?(:is_empty?) && queue.respond_to?(:peek) && !queue.is_empty?
end

Try / catch

begin
  queue.peek
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling `queue.peek` or `queue.pop` when `@size == 0`. Occurs after consuming all elements, or before the first enqueue.

Common situations: Consumer loop that pops until empty then peeks once more; queue drained by another part of the code; test running peek before any push.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/ae1e7945e281def4. Report an issue: GitHub.