krahets/hello-algo · error · IndexError

стек пуст

Error message

стек пуст

What it means

Raised by ArrayStack#pop (ru) when the stack is empty. ArrayStack backs onto Ruby's built-in Array (so there is NO capacity limit and no 'full' error ever). The guard preempts `@stack.pop`, which Ruby would otherwise return nil for — the library chooses to raise IndexError 'стек пуст' instead of silently returning nil.

Source

Thrown at ru/codes/ruby/chapter_stack_and_queue/array_stack.rb:31

  ### Получить длину стека ###
  def size
    @stack.length
  end

  ### Проверка, пуст ли стек ###
  def is_empty?
    @stack.empty?
  end

  ### Помещение в стек ###
  def push(item)
    @stack << item
  end

  ### Извлечение из стека ###
  def pop
    raise IndexError, 'стек пуст' if is_empty?

    @stack.pop
  end

  ### Доступ к верхнему элементу стека ###
  def peek
    raise IndexError, 'стек пуст' if is_empty?

    @stack.last
  end

  ### Вернуть список для вывода ###
  def to_array
    @stack
  end
end

### Driver Code ###

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with `stack.is_empty?` before pop.
  2. Drive pop loops with `while stack.size > 0`.
  3. Wrap pop in a helper returning nil on empty for optional semantics.

Example fix

// before
val = stack.pop  # raises 'стек пуст' when empty

// after
val = stack.is_empty? ? nil : stack.pop
Defensive patterns

Strategy: validation

Validate before calling

val = stack.pop unless stack.is_empty?

Type guard

def stack_nonempty?(s) = !s.is_empty?

Try / catch

begin
  val = stack.pop
rescue IndexError
  val = nil
end

Prevention

When it happens

Trigger: Calling `stack.pop` on a never-pushed stack, or after the last element was popped. Any pop loop that overshoots triggers it.

Common situations: Unwinding all frames then popping once more; mismatched push/pop counts; an algorithm that pops to verify emptiness without checking first.

Related errors


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