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
string.c
View on GitHub ↗
static VALUE
rb_str_byteindex_m(int argc, VALUE *argv, VALUE str)
{
VALUE sub;
VALUE initpos;
long pos;
if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
long slen = RSTRING_LEN(str);
pos = NUM2LONG(initpos);
if (pos < 0 ? (pos += slen) < 0 : pos > slen) {
if (RB_TYPE_P(sub, T_REGEXP)) {
rb_backref_set(Qnil);
}
return Qnil;
}
}
else {
pos = 0;
}
str_ensure_byte_pos(str, pos);
if (RB_TYPE_P(sub, T_REGEXP)) {
if (rb_reg_search(sub, str, pos, 0) >= 0) {
VALUE match = rb_backref_get();
struct re_registers *regs = RMATCH_REGS(match);
pos = BEG(0);
return LONG2NUM(pos);
}
}
else {
StringValue(sub);
pos = rb_str_byteindex(str, sub, pos);
if (pos >= 0) return LONG2NUM(pos);
}
return Qnil;
}
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
-
3.2
-
String#byteindexandString#byterindexhave been added. [Feature #13110]
-