End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method · added in Ruby 3.2
String#byteindex
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) {
pos = NUM2LONG(initpos);
}
else {
pos = 0;
}
if (pos < 0) {
pos += RSTRING_LEN(str);
if (pos < 0) {
if (RB_TYPE_P(sub, T_REGEXP)) {
rb_backref_set(Qnil);
}
return Qnil;
}
}
if (!str_check_byte_pos(str, pos)) {
rb_raise(rb_eIndexError,
"offset %ld does not land on character boundary", pos);
}
if (RB_TYPE_P(sub, T_REGEXP)) {
if (pos > RSTRING_LEN(str))
return Qnil;
if (rb_reg_search(sub, str, pos, 0) < 0) {
return Qnil;
}
else {
VALUE match = rb_backref_get();
struct re_registers *regs = RMATCH_REGS(match);
pos = BEG(0);
return LONG2NUM(pos);
}
}
else {
StringValue(sub);
pos = rb_strseq_index(str, sub, pos, 1);
}
if (pos == -1) return Qnil;
return LONG2NUM(pos);
}
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]
-