Skip to content

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

instance method · added in Ruby 3.2

String#byteindex

(::Regexp | ::string pattern, ?::int offset) -> ::Integer?
byteindex(substring, offset = 0) → integer or nil
byteindex(regexp, offset = 0) → integer or nil

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

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

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

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

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

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

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

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

If offset does not land on character (codepoint) boundary, IndexError is raised.

Related: String#index, String#byterindex.

Ruby version changes

  1. 3.2
See also #b #byterindex #ascii_only? #bytes also in 4.1 · 4.0 · 3.3 · 3.2