Arrays and Strings
Conversions between arrays and strings are quite common, so I want to give a little extra attention to the topic here. Remember that an array is a list of values, whereas a string is any quoted character (or group of characters). The to_s method will convert an array to a string by combining all of the values:
a = [1, 2, 3, 4] a.to_s # Returns "1234"
The join method does the same thing, but it takes an optional glue argument—a character (or character combination) to be placed between the array items within the string:
a.join('-') # Returns "1-2-3-4"
Turning a string into an array requires the scan or split method. I’ll demonstrate split here, and you’ll learn more about scan in Chapter 10, “Regular Expressions.” The split method breaks up a string into an array using another string (or a regular expression pattern) as the indicator of where to make the breaks. Its default separator is any white space (spaces, tabs, carriage returns, and newlines):
vowels = 'a e i o u' vowels.split
Now vowels is an array of five elements: a, e, i, o, and u. Multiple continuous spaces are ignored in such situations, as are leading and terminating white space.
If you’d like to use a different separator, provide that as an argument to the split method:
poem = %q{line 1 line 2 line 3} poem.split("\n")
After calling split on the newline character, the poem string will be turned into an array of three elements (Figure 4.13). Note that the separator will be removed from the values.
Figure 4.13 Strings can be broken on any character or character sequence you want, including newlines.
To convert arrays and strings:
Create a string containing some words:
list = 'giraffe, cat, cow, bird, dog, → rabbit, walrus'
For the sake of this example, let’s say this list of words (which was maybe read in from a file or inputted by the user) needs to be sorted, counted, and returned in alphabetical order. As a string there’s no way to do that.
Turn the string into an array:
list_array = list.split(', ')
The string will be turned into an array by splitting it up using a combination of commas plus a space. The returned value—the array—is assigned to list_array.
Count the number of words (Figure 4.14):
puts list_array.length
Figure 4.14 A string of comma-separated words is turned into an array, then counted.
Turn the array back into a string, this time in alphabetical order (Figure 4.15).
list = list_array.sort.join(', ')
Figure 4.15 The array is sorted alphabetically and then turned back into a string using join.
First the list array is sorted, and then join is applied, inserting a comma plus a space between each element to create the string. This final value of list could also be created in one step, using
list = list.split(', ').sort.join(', ')