Skip to content
instance method

String#rpartition

(::Regexp | ::string pattern) -> [ ::String, ::String, ::String ]
rpartition(pattern) → [pre_match, last_match, post_match]

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:

Example
["", "", self.dup]

If pattern is matched, returns the array:

Example
[pre_match, last_match, post_match]

where:

  • last_match is the last-found matching substring.

  • pre_match and post_match are the preceding and following substrings.

The pattern used is:

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):

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(//)      # => ["hello", "", ""]
'hello'.rpartition(/x/)     # => ["", "", "hello"]
'тест'.rpartition(/т/)      # => ["тес", "т", ""]
'こんにちは'.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):

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('')      # => ["hello", "", ""]
'тест'.rpartition('т')      # => ["тес", "т", ""]
'こんにちは'.rpartition('に') # => ["こん", "に", "ちは"]

Related: see Converting to Non-String.

Ruby version changes

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