Ruby

Split String in Ruby

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".split
=> ["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".split(",")
=> ["first", " second", " third", " fourth", " fifth"]

A simple regex expression as:

"first, second, third, fourth, fifth".split("//")
=> ["first, second, third, fourth, fifth"]

Example 3

The following example implements a simple regular expression to split the string on single whitespace.

string = "I am a new string"
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:

I
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:

string = "foo,bar,baz"
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:

string = 'This is a long string with lots of characters'
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:

This
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:

string = "Hello world."
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list