Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

String#partition

(::Regexp | ::string pattern) -> [ ::String, ::String, ::String ]
partition(string_or_regexp) → [head, match, tail]

Returns a 3-element array of substrings of self.

Matches a pattern against self, scanning from the beginning. The pattern is:

If the pattern is matched, returns pre-match, first-match, post-match:

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

If the pattern is not matched, returns a copy of self and two empty strings:

Example
'hello'.partition('x') # => ["hello", "", ""]

Related: String#rpartition, String#split.

Ruby version changes

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