String.split
Splits a string by a delimiter and converts it into an array. Commonly used for CSV parsing and text processing.
Syntax
# Splits by a delimiter and returns an array. string.split(delimiter) string.split(delimiter, limit) # Splits into individual characters and returns an array. string.chars # Splits into individual bytes and returns an array of integers. string.bytes # Splits by line and returns an array. string.lines
Method List
| Method | Description |
|---|---|
| split(sep) | Splits a string by the given delimiter and returns an array. If the argument is omitted, it splits on whitespace, treating consecutive whitespace as a single delimiter. |
| split(sep, n) | Specifies the maximum number of splits as the second argument. Any remaining content beyond the limit is collected into the last element. |
| chars | Returns an array of the string split into individual characters. |
| bytes | Splits a string into individual bytes and returns an array of their integer values. |
| lines | Returns an array of the string split by line. The newline character is included in each element. |
Sample Code
# Split by a comma.
csv = "Tanaka,Suzuki,Sato,Takahashi"
puts csv.split(",").inspect # ["Tanaka", "Suzuki", "Sato", "Takahashi"]
# Split by whitespace (when argument is omitted).
sentence = " Hello Ruby World "
puts sentence.split.inspect # ["Hello", "Ruby", "World"]
# Limit the number of splits.
data = "2024:03:15"
puts data.split(":", 2).inspect # ["2024", "03:15"]
# Split into individual characters with chars.
word = "Ruby"
puts word.chars.inspect # ["R", "u", "b", "y"]
# Split by line with lines.
multiline = "Line 1\nLine 2\nLine 3"
multiline.lines.each do |line|
puts line.chomp # Output each line with the newline removed.
end
# Split using a regular expression.
text = "one1two2three3four"
puts text.split(/\d/).inspect # ["one", "two", "three", "four"]
Notes
『split』 is the most fundamental method for converting a string into an array. When called without arguments, it treats consecutive whitespace as a single delimiter and automatically strips leading and trailing whitespace.
Trailing empty string elements are automatically removed. To preserve them, pass 『-1』 as the second argument (e.g., 『"a,,b,".split(",", -1)』).
To join a split array back into a string, use 『Array#join』. To extract a portion of a string, use 『slice / []』.
If you find any errors or copyright issues, please contact us.