Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Searches sep or pattern (regexp) in the string from the end of the string, and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.
"hello".rpartition("l")         #=> ["hel", "l", "o"]
"hello".rpartition("x")         #=> ["", "", "hello"]
"hello".rpartition(/.l/)        #=> ["he", "ll", "o"]
The match from the end means starting at the possible last position, not the last of longest matches.
"hello".rpartition(/l+/)        #=> ["hel", "l", "o"]
To partition at the last longest match, needs to combine with negative lookbehind.
"hello".rpartition(/(?<!l)l+/)  #=> ["he", "ll", "o"]
Or String#partition with negative lookforward.
"hello".partition(/l+(?!.*l)/)  #=> ["he", "ll", "o"]
               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;
        pos = rb_str_offset(str, pos);

    return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
                          rb_str_subseq(str, pos+RSTRING_LEN(sep),
    return rb_ary_new3(3, str_new_empty_String(str), str_new_empty_String(str), str_duplicate(rb_cString, str));

Was this page useful?