String#partition
str.partition(sep) Partition 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.
The fixed three-part result is the main reason to reach for partition. It gives you the separator as part of the output, which makes it easier to preserve or inspect the delimiter instead of throwing it away.
A tiny example makes the shape obvious before the longer cases below:
"name=value".partition("=")
# => ["name", "=", "value"]
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.
That makes the method easy to reason about in simple parsing code. You always know where the delimiter lives in the returned array, so the result can be unpacked without extra index math.
Because the separator is preserved, you can inspect or reuse it later without running the search again. That is useful when the delimiter itself carries meaning, such as an assignment sign or a path separator.
This direct shape is what keeps partition practical for tiny parsers and one-off scripts. You do not need a second pass to recover the separator, because the separator is already part of the value that comes back.
That makes it useful when you only care about a single split point. Instead of breaking the whole string apart, you get one clean cut and keep the rest of the text intact for later inspection.
"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.
This is the right choice when the boundary is recognizable but not fixed to one literal character. A pattern can catch repeated digits, spacing variations, or a tagged token while still giving you the exact text that matched.
"foobar".partition(/bar/)
# => ["foo", "bar", ""]
"hello123world".partition(/\d+/)
# => ["hello", "123", "world"]
"price_100_usd".partition(/_(\d+)_/)
# => ["price", "_100_", "usd"]
Using a regexp is helpful when the separator is a pattern instead of a single literal string. The middle element of the result still preserves the exact match, which is often what you want when parsing structured text.
If the match is more complex, the middle slot can also act as a quick confirmation that the pattern you expected was actually found. That is handy when you are parsing input that may contain more than one possible delimiter.
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", "", ""]
That fallback behavior makes partition predictable. If the separator is absent, the original text stays in the first slot and the empty strings make it obvious that there was no match.
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"
Destructuring is the cleanest way to use partition when you already know you need all three parts. It keeps the parsing result at the top of the local scope and avoids manual indexing.
practical example: parsing key-value pairs
partition is useful for parsing structured text where you expect a specific delimiter:
The method is especially handy when the data comes from a source that is mostly predictable, but not quite regular enough to justify a more involved parser. In that middle ground, the three-part return value gives you enough structure without much ceremony.
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=>""}
This style works well for simple key-value parsing because the returned array is already shaped for the problem. The code stays readable even if the input is missing the delimiter entirely.
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"]
split is better when you want every chunk and do not care about the delimiter. partition is better when one delimiter matters and you want the result to preserve that exact separator.