krahets/hello-algo · error · IndexError

очередь пуста

Error message

очередь пуста

What it means

Raised by ArrayQueue#peek (ru) on an empty queue. `pop` delegates to peek (`num = peek`), so the SAME raise fires for both `peek` and `pop` when size is 0. The guard protects `@nums[@front]` from being read before any element exists.

Source

Thrown at ru/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
    # Указатель head сдвигается на одну позицию назад; если он выходит за конец, то возвращается в начало массива
    @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. Guard with `queue.is_empty?` before peek or pop.
  2. Drive drain loops with `until queue.is_empty?`.
  3. Wrap pop in a helper returning nil on empty if you want optional semantics.

Example fix

// before
queue.pop  # raises 'очередь пуста' when empty

// after
item = queue.is_empty? ? nil : queue.pop
Defensive patterns

Strategy: validation

Validate before calling

item = queue.pop unless queue.is_empty?

Type guard

def queue_nonempty?(q) = !q.is_empty?

Try / catch

begin
  item = queue.pop  # also covers peek
rescue IndexError
  item = nil
end

Prevention

When it happens

Trigger: Calling `queue.peek` or `queue.pop` on an empty ArrayQueue — before any push, or after draining all elements. A consumer loop that overshoots triggers it.

Common situations: Consumer outpacing producer on the ring; popping the last item then popping again; a driver that peeks before the first push.

Related errors


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