Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
String#rpartition
static VALUE
rb_str_rpartition(VALUE str, VALUE sep)
{
rb_len_t pos;
sep = get_pat_quoted(sep, 0);
if (RB_TYPE_P(sep, T_REGEXP)) {
pos = RSTRING_LEN(str);
if (rb_reg_search(sep, str, pos, 1) < 0) {
goto failed;
}
VALUE match = rb_backref_get();
pos = RMATCH_BEG(match, 0);
sep = rb_str_subseq(str, pos, RMATCH_END(match, 0) - pos);
}
else {
/* str may have been modified by #to_str above */
pos = rb_str_sublen(str, RSTRING_LEN(str));
pos = rb_str_rindex(str, sep, pos);
if (pos < 0) {
goto failed;
}
}
rb_len_t rpos = pos + RSTRING_LEN(sep);
if (rpos > RSTRING_LEN(str)) goto failed;
return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
sep,
rb_str_subseq(str, rpos, RSTRING_LEN(str)-rpos));
failed:
return rb_ary_new3(3, str_new_empty_String(str), str_new_empty_String(str), str_duplicate(rb_cString, str));
}
Returns a 3-element array of substrings of self.
Searches self for a match of pattern, seeking the last match.
If pattern is not matched, returns the array:
["", "", self.dup]
If pattern is matched, returns the array:
[pre_match, last_match, post_match]
where:
-
last_matchis the last-found matching substring. -
pre_matchandpost_matchare the preceding and following substrings.
The pattern used is:
-
patternitself, if it is aRegexp. -
Regexp.quote(pattern), ifpatternis a string.
Note that in the examples below, a returned string 'hello' is a copy of self, not self.
If pattern is a Regexp, searches for the last matching substring (also setting matched-data global variables):
'hello'.rpartition(/l/) # => ["hel", "l", "o"] 'hello'.rpartition(/ll/) # => ["he", "ll", "o"] 'hello'.rpartition(/h/) # => ["", "h", "ello"] 'hello'.rpartition(/o/) # => ["hell", "o", ""] 'hello'.rpartition(//) # => ["hello", "", ""] 'hello'.rpartition(/x/) # => ["", "", "hello"] 'こんにちは'.rpartition(/に/) # => ["こん", "に", "ちは"]
If pattern is not a Regexp, converts it to a string (if it is not already one), then searches for the last matching substring (and does not set matched-data global variables):
'hello'.rpartition('l') # => ["hel", "l", "o"] 'hello'.rpartition('ll') # => ["he", "ll", "o"] 'hello'.rpartition('h') # => ["", "h", "ello"] 'hello'.rpartition('o') # => ["hell", "o", ""] 'hello'.rpartition('') # => ["hello", "", ""] 'こんにちは'.rpartition('に') # => ["こん", "に", "ちは"]
Related: see Converting to Non-String.
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-