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.
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"]
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
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:
The method will create an array with all the characters of the string.
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:
long string with lots of characters
The following example uses a simple regular expression to split a string into individual characters:
The above method is similar to using the split method without specifying any delimiters.
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.