Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
String#rpartition
(::Regexp | ::string pattern) -> [ ::String, ::String, ::String ]
rpartition(sep) → [head, match, tail]
string.c
View on GitHub ↗
static VALUE
rb_str_rpartition(VALUE str, VALUE sep)
{
long pos = RSTRING_LEN(str);
sep = get_pat_quoted(sep, 0);
if (RB_TYPE_P(sep, T_REGEXP)) {
if (rb_reg_search(sep, str, pos, 1) < 0) {
goto failed;
}
VALUE match = rb_backref_get();
struct re_registers *regs = RMATCH_REGS(match);
pos = BEG(0);
sep = rb_str_subseq(str, pos, END(0) - pos);
}
else {
pos = rb_str_sublen(str, pos);
pos = rb_str_rindex(str, sep, pos);
if (pos < 0) {
goto failed;
}
}
return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
sep,
rb_str_subseq(str, pos+RSTRING_LEN(sep),
RSTRING_LEN(str)-pos-RSTRING_LEN(sep)));
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.
Matches a pattern against self, scanning backwards from the end. The pattern is:
-
string_or_regexpitself, if it is aRegexp. -
Regexp.quote(string_or_regexp), ifstring_or_regexpis a string.
If the pattern is matched, returns pre-match, last-match, post-match:
Example
'hello'.rpartition('l') # => ["hel", "l", "o"] 'hello'.rpartition('ll') # => ["he", "ll", "o"] 'hello'.rpartition('h') # => ["", "h", "ello"] 'hello'.rpartition('o') # => ["hell", "o", ""] 'hello'.rpartition(/l+/) # => ["hel", "l", "o"] 'hello'.rpartition('') # => ["hello", "", ""] 'тест'.rpartition('т') # => ["тес", "т", ""] 'こんにちは'.rpartition('に') # => ["こん", "に", "ちは"]
If the pattern is not matched, returns two empty strings and a copy of self:
Example
'hello'.rpartition('x') # => ["", "", "hello"]
Related: String#partition, String#split.
Ruby version changes
-
3.0
-
The following methods now return or yield
Stringinstances instead of subclass instances when called on subclass instances: [Bug #10845]
-