krahets/hello-algo · error · IndexError

キューがいっぱいです

Error message

キューがいっぱいです

What it means

Raised by ArrayQueue#push (ja/codes/ruby/chapter_stack_and_queue/array_queue.rb:31) when the queue is full (size == capacity). Unlike Ruby's stdlib (which grows), this teaching ArrayQueue has FIXED capacity set at construction (ArrayQueue.new(n)); push guards the rear slot to avoid overwriting unread elements in the circular buffer. Message: "キューがいっぱいです" (Queue is full).

Source

Thrown at ja/codes/ruby/chapter_stack_and_queue/array_queue.rb:31

  def initialize(size)
    @nums = Array.new(size, 0) # キュー要素を格納する配列
    @front = 0 # 先頭ポインタ。先頭要素を指す
    @size = 0 # キューの長さ
  end

  ### キューの容量を取得 ###
  def capacity
    @nums.length
  end

  ### キューが空か判定 ###
  def is_empty?
    size.zero?
  end

  ### エンキュー ###
  def push(num)
    raise IndexError, 'キューがいっぱいです' if size == capacity

    # 末尾ポインタを計算し、末尾インデックス + 1 を指す
    # 剰余演算により、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

View on GitHub (pinned to 69932aed18)

Solutions

  1. Construct ArrayQueue.new with a capacity larger than your maximum live element count.
  2. Drain (pop) before pushing when size == capacity, or skip the push if stale data is acceptable.
  3. Switch to a growable structure (linked-list queue, or stdlib) if the bound is unknown — this ArrayQueue cannot resize.

Example fix

# before
queue = ArrayQueue.new(5)
6.times { |i| queue.push(i) } # raises on the 6th

# after
queue = ArrayQueue.new(10) # size to your peak live count
# or guard:
queue.push(x) unless queue.size == queue.capacity
Defensive patterns

Strategy: validation

Validate before calling

queue.push(num) unless queue.size == queue.capacity

Type guard

def queue_has_room?(q); q.respond_to?(:size) && q.respond_to?(:capacity) && q.size < q.capacity; end

Try / catch

begin
  queue.push(num)
rescue IndexError
  # full: drop oldest, resize via new instance, or back-pressure
  queue.pop
  retry
end

Prevention

When it happens

Trigger: Calling queue.push(num) when queue.size == queue.capacity. Occurs after filling all n slots without popping, or in a circular enqueue/dequeue loop that enqueues more than it dequeues. Note: the English sibling (array_queue.rb) raises "Queue is full" with the same trigger.

Common situations: Constructing the queue with too small a capacity for the workload; producer outrunning the consumer in a fixed buffer; reusing the driver's size-10 queue for more than 10 simultaneous items.

Related errors


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