Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#find_index

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

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

Related: rindex.

See also #filter! #first #filter #flatten also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0