Ruby offers a collection of methods you can use to work with and manipulate strings. One fundamental string manipulation operation is splitting a string.
You can split a string into substrings and act on the resulting values. Using the Ruby split method, you can specify your string and the parameters to split the string.
This guide will discuss how to break down a string into various substrings in Ruby using the split method.
Basic Usage – Example 1
To use the split method, call the method against a string literal as:
=> ["Hello", "world", "foo"]
The method will return an array of the string characters.
Example 2
By default, the split method will break down the string based on a space delimiter. However, you can specify a custom delimiter, including a regular expression.
For example, to split a string on a comma, we can do:
=> ["first", " second", " third", " fourth", " fifth"]
A simple regex expression as:
=> ["first, second, third, fourth, fifth"]
Example 3
The following example implements a simple regular expression to split the string on single whitespace.
puts string.split(/ /, 2)
Once the split function encounters the first occurrence of a whitespace character, it will split the string and terminate.
Output from the above example is as:
am a new string
Example 4
If we call the split method and provide no delimiter condition, it will return an array of characters of the passed string.
Take the following example:
puts string.split('')
The method will create an array with all the characters of the string.
Example 5
The split method also allows you to specify the limit for the number of returned values.
Consider the example below:
puts string.split(' ', 4)
The above example will only split using the specified delimiter up to the limit set. In this example, it returns three split values as shown:
is
a
long string with lots of characters
Example 6
The following example uses a simple regular expression to split a string into individual characters:
puts string.split(%r{\s*})
The above method is similar to using the split method without specifying any delimiters.
Conclusion
This guide covers various ways to split a Ruby string using the built-in split method. Feel free to experiment with the techniques and multiple variations of regular expressions.