krahets/hello-algo · error · IndexError
двусторонняя очередь пуста
Error message
двусторонняя очередь пуста
What it means
Raised by ArrayDeque#peek_first (ru) when the deque is empty. Because `pop_first` is implemented as `num = peek_first; @front = index(@front + 1); @size -= 1`, the SAME raise surfaces for both `peek_first` and `pop_first` on an empty deque. Note: unlike array_queue.push, the push methods here only `puts`+`return` on full — they never raise — so this is the only IndexError in the file.
Source
Thrown at ru/codes/ruby/chapter_stack_and_queue/array_deque.rb:76
### Извлечение из головы очереди ###
def pop_first
num = peek_first
# Указатель головы сдвигается на одну позицию назад
@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...sizeView on GitHub (pinned to 69932aed18)
Solutions
- Guard with `deque.is_empty?` before peek_first or pop_first.
- Drive drain loops with `until deque.is_empty?`.
- Use to_array (empty-safe) when you only need to inspect contents.
Example fix
// before deque.pop_first # raises 'двусторонняя очередь пуста' when empty // after val = deque.is_empty? ? nil : deque.pop_first
Defensive patterns
Strategy: validation
Validate before calling
val = deque.pop_first unless deque.is_empty?
Type guard
def deque_nonempty?(d) = !d.is_empty?
Try / catch
begin val = deque.pop_first # also covers peek_first rescue IndexError val = nil end
Prevention
- pop_first routes through peek_first — guard covers both.
- Drive drain loops with `until deque.is_empty?`.
- Note push_* only puts+returns on full — it never raises, so capacity is silent here.
When it happens
Trigger: Calling `deque.peek_first` or `deque.pop_first` on an empty ArrayDeque (size 0), e.g. before any push, or after draining from both ends.
Common situations: A consumer loop that pops_first until empty then peeks; reading the front for display after a drain; mismatched push/pop counts in a driver block.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/2201bda92674710a.
Report an issue: GitHub.