String#partition

str.partition(sep)
Returns: Array · Updated March 14, 2026 · String Methods
ruby string splitting parsing

The partition method searches for a separator pattern within the string and splits it into three parts. It always returns a 3-element array containing the portion before the separator, the separator itself, and the portion after the separator.

This method is particularly useful when you need to parse structured text where a specific delimiter is expected to appear exactly once, such as key-value pairs or file paths.

Basic Usage

When the separator is found, partition returns an array with three elements: the substring before the match, the matching separator, and the substring after the match.

"hello world".partition(" ")
# => ["hello", " ", "world"]

"red,green,blue".partition(",")
# => ["red", ",", "green,blue"]

"/path/to/file".partition("/")
# => ["", "/", "path/to/file"]

Using a Regex Pattern

You can also pass a regular expression as the separator. The match captured by the regex becomes the middle element of the returned array. This is powerful for extracting structured data from strings.

"foobar".partition(/bar/)
# => ["foo", "bar", ""]

"hello123world".partition(/\d+/)
# => ["hello", "123", "world"]

"price_100_usd".partition(/_(\d+)_/)
# => ["price", "_100_", "usd"]

When Separator Is Not Found

If the separator is not found, partition returns the original string as the first element, with two empty strings filling the second and third positions:

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

"no separator here".partition(":")
# => ["no separator here", "", ""]

Destructuring Assignment

Ruby allows you to destructure the returned array directly, making partition convenient for extracting multiple values in a single line:

key, sep, value = "username=john".partition("=")
key   # => "username"
sep   # => "="
value # => "john"

Practical Example: Parsing Key-Value Pairs

partition is useful for parsing structured text where you expect a specific delimiter:

def parse_key_value(str)
  key, sep, value = str.partition("=")
  { key: key, separator: sep, value: value }
end

parse_key_value("username=john")
# => {:key=>"username", :separator=>"=", :value=>"john"}

parse_key_value("invalid")
# => {:key=>"invalid", :separator=>"", :value=>""}

Comparison with Split

Unlike split, which returns an array of all parts, partition always returns exactly three elements. This makes it ideal for cases where you need to preserve the delimiter:

# split - loses the delimiter
"a-b-c".split("-")
# => ["a", "b", "c"]

# partition - keeps the delimiter
"a-b-c".partition("-")
# => ["a", "-", "b-c"]

See Also