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.
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")
View all Courses