Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#index

array.index(object) → integer or nil
array.index {|element| ... } → integer or nil
array.index → new_enumerator

Alias of #find_index

Returns the index of a specified element.

When argument object is given but no block, returns the index of the first element element for which object == element:

Example
a = [:foo, 'bar', 2, 'bar']
a.index('bar') # => 1

Returns nil if no such element found.

When both argument object and a block are given, calls the block with each successive element; returns the index of the first element for which the block returns a truthy value:

Example
a = [:foo, 'bar', 2, 'bar']
a.index {|element| element == 'bar' } # => 1

Returns nil if the block never returns a truthy value.

When neither an argument nor a block is given, returns a new Enumerator:

Example
a = [:foo, 'bar', 2]
e = a.index
e # => #<Enumerator: [:foo, "bar", 2]:index>
e.each {|element| element == 'bar' } # => 1

Array#find_index is an alias for Array#index.

Related: rindex.

See also #find_index #include? #initialize_copy #hash also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1