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

String#index

string.index(substring, offset = 0) → integer or nil
string.index(regexp, offset = 0) → integer or nil

Returns the Integer index of the first occurrence of the given substring, or nil if none found:

Example
'foo'.index('f') # => 0
'foo'.index('o') # => 1
'foo'.index('oo') # => 1
'foo'.index('ooo') # => nil

Returns the Integer index of the first match for the given Regexp regexp, or nil if none found:

Example
'foo'.index(/f/) # => 0
'foo'.index(/o/) # => 1
'foo'.index(/oo/) # => 1
'foo'.index(/ooo/) # => nil

Integer argument offset, if given, specifies the position in the string to begin the search:

Example
'foo'.index('o', 1) # => 1
'foo'.index('o', 2) # => 2
'foo'.index('o', 3) # => nil

If offset is negative, counts backward from the end of self:

Example
'foo'.index('o', -1) # => 2
'foo'.index('o', -2) # => 1
'foo'.index('o', -3) # => 1
'foo'.index('o', -4) # => nil

Related: String#rindex

See also #include? #initialize_copy #hex #insert also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1