Skip to content
instance method

String#partition

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

Returns a 3-element array of substrings of self.

If pattern is matched, returns the array:

Example
[pre_match, first_match, post_match]

where:

  • first_match is the first-found matching substring.

  • pre_match and post_match are the preceding and following substrings.

If pattern is not matched, returns the array:

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

Note that in the examples below, a returned string 'hello' is a copy of self, not self.

If pattern is a Regexp, performs the equivalent of self.match(pattern) (also setting matched-data variables):

Example
'hello'.partition(/h/)  # => ["", "h", "ello"]
'hello'.partition(/l/)  # => ["he", "l", "lo"]
'hello'.partition(/l+/) # => ["he", "ll", "o"]
'hello'.partition(/o/)  # => ["hell", "o", ""]
'hello'.partition(/^/)  # => ["", "", "hello"]
'hello'.partition(//)   # => ["", "", "hello"]
'hello'.partition(/$/)  # => ["hello", "", ""]
'hello'.partition(/x/)  # => ["hello", "", ""]

If pattern is not a Regexp, converts it to a string (if it is not already one), then performs the equivalent of self.index(pattern) (and does not set matched-data global variables):

Example
'hello'.partition('h')     # => ["", "h", "ello"]
'hello'.partition('l')     # => ["he", "l", "lo"]
'hello'.partition('ll')    # => ["he", "ll", "o"]
'hello'.partition('o')     # => ["hell", "o", ""]
'hello'.partition('')      # => ["", "", "hello"]
'hello'.partition('x')     # => ["hello", "", ""]
'тест'.partition('т')      # => ["", "т", "ест"]
'こんにちは'.partition('に') # => ["こん", "に", "ちは"]

Related: see Converting to Non-String.

Ruby version changes

  1. 3.0
See also #ord #prepend #oct #replace also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0