krahets/hello-algo · error · IndexError

Index out of bounds

Error message

Index out of bounds

What it means

Raised by `MyList#get` (my_list.rb:23) when `index < 0 || index >= size`. This is a dynamic-array list implementation; the guard enforces that reads stay within the logical `[0, size)` range (not the underlying `@capacity`). It returns `@arr[index]`, so an out-of-range index would read uninitialized filler slots.

Source

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

=end

### List class ###
class MyList
  attr_reader :size       # Get list length (current number of elements)
  attr_reader :capacity   # Get list capacity

  ### Constructor ###
  def initialize
    @capacity = 10
    @size = 0
    @extend_ratio = 2
    @arr = Array.new(capacity)
  end

  ### Access element ###
  def get(index)
    # If the index is out of bounds, throw an exception, as below
    raise IndexError, "Index out of bounds" if index < 0 || index >= size
    @arr[index]
  end

  ### Access element ###
  def set(index, num)
    raise IndexError, "Index out of bounds" if index < 0 || index >= size
    @arr[index] = num
  end

  ### Add element at end ###
  def add(num)
    # When the number of elements exceeds capacity, trigger the extension mechanism
    extend_capacity if size == capacity
    @arr[size] = num

    # Update the number of elements
    @size += 1
  end

View on GitHub (pinned to 69932aed18)

Solutions

  1. Validate `0 <= index && index < list.size` before calling `get`.
  2. Use `list.size` (not capacity) as the upper bound in iteration.
  3. Recompute or invalidate indices after `remove`/`insert`.

Example fix

# before
val = list.get(i)

# after
val = (0...list.size).include?(i) ? list.get(i) : nil
Defensive patterns

Strategy: validation

Validate before calling

return nil unless (0...list.size).include?(index)
list.get(index)

Type guard

def valid_list_index?(list, index)
  index.is_a?(Integer) && index >= 0 && index < list.size
end

Try / catch

begin
  list.get(index)
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling `list.get(i)` with `i` negative, `i >= list.size`, or `i` computed from an off-by-one loop. Also when `size` has been decremented by `remove` but the caller caches a stale index.

Common situations: Loop using `<= size` instead of `< size`; index from an external source not bounds-checked; stale index after a concurrent or sequential remove shifts elements.

Related errors


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