krahets/hello-algo · error · IndexError

индекс выходит за границы

Error message

индекс выходит за границы

What it means

Raised by MyList#get (ru) when the requested index is outside `[0, size)`. The list is a hand-rolled dynamic array with a separate `@size` (logical length) and `@capacity`; the guard `raise IndexError, "индекс выходит за границы" if index < 0 || index >= size` rejects reads past the last populated slot, even if the backing array has spare capacity.

Source

Thrown at ru/codes/ruby/chapter_array_and_linkedlist/my_list.rb:23

=end

### Класс списка ###
class MyList
  attr_reader :size       # Получить длину списка (текущее число элементов)
  attr_reader :capacity   # Получить вместимость списка

  ### Конструктор ###
  def initialize
    @capacity = 10
    @size = 0
    @extend_ratio = 2
    @arr = Array.new(capacity)
  end

  ### Доступ к элементу ###
  def get(index)
    # Если индекс выходит за границы, выбрасывается исключение; далее аналогично
    raise IndexError, "индекс выходит за границы" if index < 0 || index >= size
    @arr[index]
  end

  ### Доступ к элементу ###
  def set(index, num)
    raise IndexError, "индекс выходит за границы" if index < 0 || index >= size
    @arr[index] = num
  end

  ### Добавление элемента в конец ###
  def add(num)
    # При превышении вместимости по числу элементов запускается расширение
    extend_capacity if size == capacity
    @arr[size] = num

    # Обновить число элементов
    @size += 1
  end

View on GitHub (pinned to 69932aed18)

Solutions

  1. Bound lookups by `list.size`, e.g. iterate `0...list.size`.
  2. Validate `index.between?(0, list.size - 1)` before calling get.
  3. After remove(), remember all higher indices shift down by one.

Example fix

// before
v = list.get(i)  # raises if i >= size

// after
v = (i >= 0 && i < list.size) ? list.get(i) : nil
Defensive patterns

Strategy: validation

Validate before calling

v = list.get(i) if i.between?(0, list.size - 1)

Type guard

def valid_get_index?(list, i) = i.between?(0, list.size - 1)

Try / catch

begin
  v = list.get(i)
rescue IndexError
  v = nil
end

Prevention

When it happens

Trigger: Calling `list.get(i)` with i negative, i >= size, or after elements were removed so size shrank below a previously-valid index. Indexing with a value computed from capacity rather than size also triggers it.

Common situations: Using `list.capacity` instead of `list.size` as the loop bound; off-by-one in a for loop (`0..size` inclusive vs `0...size`); reading a slot after a remove shifted indices down.

Related errors


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