krahets/hello-algo · error · IndexError

雙向佇列為空

Error message

雙向佇列為空

What it means

Raised by peek_first of the ArrayDeque teaching class (a circular-array double-ended queue) when is_empty? is true. It prevents reading from @nums[@front] when the deque holds zero elements, which would return stale or zero data. The guard fires before any array read.

Source

Thrown at zh-hant/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. Return a default value when empty: deque.is_empty? ? nil : deque.peek_first.
  3. Track push/pop counts externally to detect state mismatches.
  4. Note that push_first/push_last do NOT raise on full — they print and return nil — so verify the push succeeded before relying on peek.

Example fix

# before
first = deque.peek_first  # raises if deque was drained

# after
first = 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

# Ruby: safe peek_first
def safe_peek_first(deque)
  deque.is_empty? ? nil : deque.peek_first
end

Try / catch

begin
  first = deque.peek_first
rescue IndexError
  first = nil
end

Prevention

When it happens

Trigger: Calling deque.peek_first on a newly constructed deque (size 0), calling it after all elements have been popped, or calling pop_first (which internally calls peek_first) on an empty deque.

Common situations: Assuming the deque has elements after a failed push (push_first/push_last silently print '已滿' instead of raising); draining the deque then peeking; using peek as a default value without an emptiness guard.

Related errors


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