krahets/hello-algo · error · IndexError

双向队列为空

Error message

双向队列为空

What it means

Raised by `ArrayDeque#peek_first` (array_deque.rb:76) when `is_empty?` is true. `peek_first` reads `@nums[@front]` to expose the front element without removing it; on an empty deque `@front` is stale and `@size` is zero, so the read would return garbage or nil. The guard ensures callers never see an uninitialized slot.

Source

Thrown at codes/ruby/chapter_stack_and_queue/array_deque.rb:76

  ### 队首出队 ###
  def pop_first
    num = peek_first
    # 队首指针向后移动一位
    @front = index(@front + 1)
    @size -= 1
    num
  end

  ### 队尾出队 ###
  def pop_last
    num = peek_last
    @size -= 1
    num
  end

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

    @nums[@front]
  end

  ### 访问队尾元素 ###
  def peek_last
    raise IndexError, '双向队列为空' if is_empty?

    # 计算尾元素索引
    last = index(@front + size - 1)
    @nums[last]
  end

  ### 返回数组用于打印 ###
  def to_array
    # 仅转换有效长度范围内的列表元素
    res = []
    for i in 0...size

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check `deque.is_empty?` before calling `peek_first` or `pop_first`.
  2. Use `deque.size.zero?` explicitly if readability matters.
  3. If empty peek is a normal control-flow signal, rescue IndexError at the call site.

Example fix

# before
front = deque.peek_first

# after
front = deque.is_empty? ? nil : deque.peek_first
Defensive patterns

Strategy: validation

Validate before calling

return nil if deque.is_empty?
deque.peek_first

Type guard

def deque_readable?(deque)
  deque.respond_to?(:is_empty?) && deque.respond_to?(:peek_first) && !deque.is_empty?
end

Try / catch

begin
  deque.peek_first
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling `deque.peek_first` (or `pop_first`, which delegates to it) on a deque whose `@size == 0`. Occurs after draining all elements, or immediately after construction before any push.

Common situations: Deque used as a sliding-window buffer that gets fully consumed between batches; calling peek before the first enqueue; off-by-one in a consume loop.

Related errors


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