Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
string
array
split

How to convert a string to an array in Ruby using split method

Natasha Waller

We can easily convert a string to an array in Ruby using the split method. Think of this method as a pair of scissors, and the string you will be converting as a literal piece of string. Just as you can take your pair of scissors and “split” a piece of string into individual parts based on where you place your scissors, so can we tell the split method to make cuts based on specific words, characters, or spaces.

Code

The general syntax for using the split method is string.split(). The place at which to split the string is specified as an argument to the method.

The split substrings will be returned together in an array.

In the following example, we will convert a string to an array based on the empty spaces between the words.

str = "This can be split into smaller pieces"
print str.split(" ")

Here, we will change a one-word string into an array of individual characters.

str = "scissors"
print str.split("")

Finally, we will split a string into an array based on a specific word.

str = "This can be split into smaller pieces"
print str.split("into")

RELATED TAGS

ruby
string
array
split
RELATED COURSES

View all Courses

Keep Exploring