krahets/hello-algo · error · IndexError

両端キューは空です

Error message

両端キューは空です

What it means

Raised by ArrayDeque#peek_first (ja/codes/ruby/chapter_stack_and_queue/array_deque.rb:76) when the deque is empty. It returns @nums[@front], undefined when size == 0, so the guard blocks the read. pop_first delegates to peek_first, so removing from the front of an empty deque surfaces this too. Message: "両端キューは空です" (Deque is empty).

Source

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

  ### キュー先頭から取り出す ###
  def pop_first
    num = peek_first
    # 先頭ポインタを 1 つ後ろへ進める
    @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 peek_first/pop_first.
  2. Verify deque.size >= 1 before any front-side operation.
  3. Rescue IndexError and return nil for the empty case if empty is expected.

Example fix

# before
front = deque.peek_first # raises on empty

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

Strategy: validation

Validate before calling

deque.peek_first unless deque.is_empty?

Type guard

def deque_nonempty?(d); d.respond_to?(:is_empty?) && !d.is_empty?; end

Try / catch

begin
  deque.peek_first
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling deque.peek_first or deque.pop_first when deque.size == 0 — before any push, or after the deque has been fully drained.

Common situations: A two-ended buffer drained from both sides past empty; deque used as a sliding window with off-by-one length checks; test harness popping in a loop without an emptiness guard.

Related errors


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