krahets/hello-algo · error · IndexError

キューは空です

Error message

キューは空です

What it means

Raised by ArrayQueue#peek (ja/codes/ruby/chapter_stack_and_queue/array_queue.rb:52) when the queue is empty. It returns @nums[@front], invalid when size == 0, so the guard blocks the read. pop calls peek first, so dequeue on an empty queue surfaces this too. Message: "キューは空です" (Queue is empty). Japanese mirror of error 540.

Source

Thrown at ja/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
    # 先頭ポインタを1つ後ろへ進め、末尾を越えたら配列先頭に戻す
    @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 peek/pop.
  2. Keep enqueued and dequeued counts balanced.
  3. Rescue IndexError around dequeue and treat empty as idle.

Example fix

# before
queue = ArrayQueue.new(10)
queue.pop # raises IndexError, "キューは空です"

# after
queue.pop unless queue.is_empty?
Defensive patterns

Strategy: validation

Validate before calling

queue.pop unless queue.is_empty?

Type guard

def queue_nonempty?(q); q.respond_to?(:is_empty?) && !q.is_empty?; end

Try / catch

begin
  queue.pop
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling queue.peek or queue.pop when queue.size == 0 — before the first push, or after the front pointer has advanced past every element.

Common situations: Draining a circular queue past empty in a producer/consumer loop; consumer outrunning the producer; test code popping more than it pushed.

Related errors


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