krahets/hello-algo · error · IndexError

インデックスが範囲外です

Error message

インデックスが範囲外です

What it means

Raised by MyList#get (ja/codes/ruby/chapter_array_and_linkedlist/my_list.rb:23) when index is out of bounds (index < 0 or index >= size). MyList is the teaching re-implementation of a dynamic array; get reads @arr[index], so it guards the index explicitly like a real list would. The message is Japanese: "Index is out of range".

Source

Thrown at ja/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. Validate 0 <= index < list.size before calling get.
  2. Use list.size (not a stale local) as the loop bound; iterate with 0...size.
  3. Rescue IndexError for optional access and return nil when out of range.

Example fix

# before
list.get(list.size) # raises; one past the end

# after
list.get(index) if index.between?(0, list.size - 1)
Defensive patterns

Strategy: validation

Validate before calling

list.get(index) if index.between?(0, list.size - 1)

Type guard

def valid_index?(list, i); i.is_a?(Integer) && i.between?(0, list.size - 1); end

Try / catch

begin
  list.get(index)
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling list.get(index) with index < 0 or index >= list.size. Commonly: get(list.size) (off-by-one), get(-1), or calling get after remove shortened the list without updating the caller's stored length.

Common situations: Off-by-one loops using <= size instead of < size; using a cached length that went stale after remove; iterating backward past 0; porting code that assumed Ruby's negative-index semantics.

Related errors


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