krahets/hello-algo · error · IndexError

佇列為空

Error message

佇列為空

What it means

Raised by the peek method of the ArrayQueue teaching class when is_empty? is true. It prevents reading @nums[@front] when no elements are enqueued, which would return stale zero-initialized data. Note that pop also calls peek internally, so popping an empty queue propagates this error.

Source

Thrown at zh-hant/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. Check queue.is_empty? before calling peek or pop.
  2. Return nil or a sentinel for empty: queue.is_empty? ? nil : queue.peek.
  3. Use while !queue.is_empty? for safe draining.
  4. Track enqueue/dequeue counts to catch mismatches.

Example fix

# before
head = queue.peek  # raises if queue is empty

# 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

# Ruby: safe peek
def safe_peek(queue)
  queue.is_empty? ? nil : queue.peek
end

Try / catch

begin
  head = queue.peek
rescue IndexError
  head = nil
end

Prevention

When it happens

Trigger: Calling queue.peek or queue.pop on a newly constructed queue (size 0), calling them after all elements have been dequeued, or calling them in a drain loop that overshoots.

Common situations: Peeking or popping without checking emptiness; a consumer reading faster than the producer enqueues; using a fixed-count loop instead of a while !is_empty? loop to drain.

Related errors


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