Skip to content
instance method · added in Ruby 3.2

String#byteindex

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

Returns the 0-based integer index of a substring of self specified by object (a string or Regexp) and offset, or nil if there is no such substring; the returned index is the count of bytes (not characters).

When object is a string, returns the index of the first found substring equal to object:

Example
s = 'foo'          # => "foo"
s.size             # => 3 # Three 1-byte characters.
s.bytesize         # => 3 # Three bytes.
s.byteindex('f')   # => 0
s.byteindex('o')   # => 1
s.byteindex('oo')  # => 1
s.byteindex('ooo') # => nil

When object is a Regexp, returns the index of the first found substring matching object; updates Regexp-related global variables:

Example
s = 'foo'
s.byteindex(/f/)   # => 0
$~                 # => #<MatchData "f">
s.byteindex(/o/)   # => 1
s.byteindex(/oo/)  # => 1
s.byteindex(/ooo/) # => nil
$~                 # => nil

Integer argument offset, if given, specifies the 0-based index of the byte where searching is to begin.

When offset is non-negative, searching begins at byte position offset:

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

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

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

Raises IndexError if the byte at offset is not the first byte of a character:

Example
s = "\uFFFF\uFFFF"       # => "\uFFFF\uFFFF"
s.size                   # => 2 # Two 3-byte characters.
s.bytesize               # => 6 # Six bytes.
s.byteindex("\uFFFF")    # => 0
s.byteindex("\uFFFF", 1) # Raises IndexError
s.byteindex("\uFFFF", 2) # Raises IndexError
s.byteindex("\uFFFF", 3) # => 3
s.byteindex("\uFFFF", 4) # Raises IndexError
s.byteindex("\uFFFF", 5) # Raises IndexError
s.byteindex("\uFFFF", 6) # => nil

Related: see Querying.

Ruby version changes

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