Skip to content

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

instance method

String#partition

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

Searches sep or pattern (regexp) in 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".partition("l")         #=> ["he", "l", "lo"]
"hello".partition("x")         #=> ["hello", "", ""]
"hello".partition(/.l/)        #=> ["h", "el", "lo"]

Ruby version changes

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