String#split
str.split(pattern=nil, limit=nil) -> array The split method breaks a string into an array of substrings using a specified delimiter pattern. It’s one of the most frequently used string methods in Ruby, essential for parsing CSV data, processing text files, tokenizing user input, and manipulating delimited strings. When no pattern is provided, split defaults to splitting on whitespace while also collapsing consecutive whitespace characters and trimming leading/trailing empty strings.
The method is useful because it turns a text-format decision into a single, readable call. That makes it a natural first step when you are dealing with logs, command output, or data that is already arranged as separators and fields. The shape of the result is predictable, which is why split shows up so often in small scripts and larger parsers alike.
Syntax
str.split(pattern=nil, limit=nil)
The method takes an optional pattern (string or regex) and an optional limit integer. Both parameters have sensible defaults when omitted. That makes split a flexible first step for cleaning input before you decide whether the data needs more specialized parsing.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
pattern | String or Regexp | nil (whitespace) | The delimiter to split on. Can be a plain string, a regular expression, or nil to split on whitespace. |
limit | Integer | nil (unlimited) | Maximum number of elements to return. When positive, returns at most limit elements with the last element containing the remainder. When negative, returns all elements without collapsing trailing empty strings. |
Examples
Splitting on a string delimiter
# Basic string split on comma
"apple,banana,cherry".split(",")
# => ["apple", "banana", "cherry"]
# Split on space
"hello world".split(" ")
# => ["hello", "world"]
# Split on multi-character delimiter
"one|||two|||three".split("|||")
# => ["one", "two", "three"]
This is the simplest form of split, and it works best when the separator is already known. If the delimiter changes from line to line, a regex is often easier to maintain. The string form also works with multi-character delimiters like "|||", so you are not limited to single-character separators when the data uses a longer token to mark field boundaries.
Splitting with a regex pattern
# Split on one or more whitespace characters
"one two\nthree \tfour".split(/\s+/)
# => ["one", "two", "three", "four"]
# Split on digits
"abc123def456ghi".split(/\d+/)
# => ["abc", "def", "ghi"]
# Split on multiple delimiters with regex alternation
"a,b;c:d".split(/[,:;]/)
# => ["a", "b", "c", "d"]
Regex-based splitting is a better fit when the input has several valid separators or inconsistent spacing. It keeps the parsing rule in one place instead of spreading string cleanup across the rest of the code. The alternation operator | inside a regex character class lets you split on commas, semicolons, or colons simultaneously, which is common when parsing loosely formatted config files or user-supplied lists.
Using the limit parameter
# Limit to first N elements
"a,b,c,d,e".split(",", 3)
# => ["a", "b", "c,d,e"]
# Negative limit keeps trailing empty strings
"a,b,c,,".split(",", -1)
# => ["a", "b", "c", "", ""]
# Default behavior (no limit) removes trailing empties
"a,b,c,,".split(",")
# => ["a", "b", "c"]
# Limit of 1 returns the whole string as single element
"hello world".split(" ", 1)
# => ["hello world"]
The limit argument is helpful when you only want part of the input and want Ruby to leave the remainder intact. That can make log parsing and simple command parsing easier to read. A positive limit tells Ruby “give me at most this many pieces,” which is useful when you want to separate a header from a body without splitting the body further.
Splitting without arguments
# No arguments = split on whitespace
" one two three ".split
# => ["one", "two", "three"]
# Multiple spaces/newlines are treated as single delimiter
"one\n\n\ntwo\t\tthree".split
# => ["one", "two", "three"]
The limit argument is helpful when you only want part of the input and want Ruby to leave the remainder intact. That can make log parsing and simple command parsing easier to read. A positive limit tells Ruby “give me at most this many pieces,” which is useful when you want to separate a header from a body without splitting the body further.
When no pattern is given, Ruby trims surrounding whitespace and collapses repeated separators. That default is convenient for tokenizing plain text, especially when the spacing is messy or inconsistent.
Common Patterns
Parsing CSV data
# Simple CSV parsing
csv_line = "John,Doe,30,New York"
fields = csv_line.split(",")
# => ["John", "Doe", "30", "New York"]
# Handling quoted fields requires a more complex regex
# but split gets you started quickly
That lightweight approach works for simple comma-separated records, but it is not a full CSV parser. Once quoting or escaping enters the picture, a dedicated CSV library is usually the safer choice. For quick scripts and one-off data munging, however, a simple split(",") is often all you need to turn a line of values into something you can iterate over or filter.
Tokenizing user input
# Split sentence into words
sentence = "The quick brown fox jumps"
words = sentence.split
# => ["The", "quick", "brown", "fox", "jumps"]
# Get first N words only
first_two = sentence.split[0..1]
# => ["The", "quick"]
Tokenizing user input is one of the most common uses for split because the output is easy to index and slice. After the split, the array methods you already know do the rest of the work. The no-argument form is especially convenient for tokenizing because it handles irregular whitespace without any extra configuration, giving you clean word tokens in a single call.
Processing log files
# Split log entry on pipe character
log_entry = "2024-01-15|ERROR|Connection timeout"
parts = log_entry.split("|")
date, level, message = parts
# date = "2024-01-15", level = "ERROR", message = "Connection timeout"
Splitting log lines by a known separator keeps the parsing step compact and readable. If the log format is stable, the array assignment can often describe the structure more clearly than a custom parser. The parallel assignment date, level, message = parts is a Ruby idiom that works particularly well with split because the method’s return value is already a flat array.
Extracting numbers from strings
# Pull all numbers out of a string
text = "Order #12345 for $99.99"
numbers = text.split(/[^0-9]+/).reject(&:empty?)
# => ["12345", "99", "99"]
This pattern is useful when you only care about numeric fragments and can ignore the separators between them. It is a small, readable way to pull out values without writing a manual scanner. The reject(&:empty?) call cleans up any leading or trailing empty strings that the regex split produces, which keeps the result array tidy and ready for further processing.
Splitting by newlines
# Split text into lines
multiline = "line one\nline two\nline three"
lines = multiline.split("\n")
# => ["line one", "line two", "line three"]
# Or use regex for cross-platform compatibility
lines = multiline.split(/\r?\n/)
# => ["line one", "line two", "line three"]
When you are working with text files, newline splitting is often the bridge between raw text and line-oriented processing. The regex version gives you consistent behavior across Unix and Windows line endings. For most practical purposes, split("\n") and split(/\r?\n/) are the two patterns you will reach for, and the regex variant is safer when the input might come from a Windows source.
Errors
ArgumentError
# Limit must be an integer
"a,b,c".split(",", "three")
# => ArgumentError: limit must be an integer
The ArgumentError for a non-integer limit is straightforward: Ruby expects an Integer and nothing else. If you are reading the limit from user input or a configuration file, convert it with to_i before passing it to split. A non-numeric string will become 0, which has its own special behavior, so a bounds check after conversion is a good idea.
RegexpError
# Invalid regex pattern
"test".split(/[/)
# => RegexpError: unmatched close parenthesis
Regex errors from split are the same as any regex error in Ruby: a malformed pattern will raise RegexpError immediately. The best defense is to test regex patterns in isolation before passing them to split, especially when the pattern is built dynamically from user input or configuration files. A quick Regexp.new call in a test can catch syntax problems before they reach the parsing code.
Special cases with empty strings
# Splitting empty string
"".split(",")
# => []
# Splitting on empty string (Ruby 3.1+)
# "hello".split("")
# => ["h", "e", "l", "l", "o"]
# In older Ruby versions, this behavior differs
# Splitting with limit 0 returns nil
# Note: limit 0 is treated specially and returns nil
# "a,b,c".split(",", 0)
# => nil
These edge cases are worth keeping in mind because split does not always return the same shape of array. The limit and empty-string behavior can change the output in ways that matter to later array indexing.
When split is doing its job well, the code around it stays straightforward: parse once, then work with the array. If you find yourself building a large amount of cleanup after splitting, it may be a sign that the input format needs a more precise parser or a smaller delimiter rule. A well-chosen split call should produce an array that is already close to the shape you need, so the next step is typically iteration or deconstruction rather than further sanitization.
See Also
- Array#join — The inverse of split; joins array elements into a string
- String#scan — Extracts all matches of a pattern into an array
- Array#flatten — Flattens nested arrays after splitting