Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#rpartition

str.rpartition(sep) → [head, sep, tail]
str.rpartition(regexp) → [head, match, tail]

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.

Example
"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.

Example
"hello".rpartition(/l+/)        #=> ["hel", "l", "o"]

To partition at the last longest match, needs to combine with negative lookbehind.

Example
"hello".rpartition(/(?<!l)l+/)  #=> ["he", "ll", "o"]

Or String#partition with negative lookforward.

Example
"hello".partition(/l+(?!.*l)/)  #=> ["he", "ll", "o"]

Ruby version changes

  1. 3.0
See also #rjust #rstrip #rindex #rstrip! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0