Arrays, Ranges, and Hashes in Ruby
Chapter 3, “Simple Types,” concentrates on the most basic kinds of data used in Ruby, primarily numbers and strings. I call these simple types because such variables represent only a single value. In this chapter you’ll learn ways to represent multiple values using just one variable. These more complex data types include arrays, ranges, and hashes.
In the examples, you’ll learn how to create variables of these types, add and remove values, and manipulate them using different methods. In Chapter 5, “Control Structures,” you’ll see how to iterate through these types, accessing the individual values one at a time. How to create and use the most important complex data type—objects—will be discussed in Chapter 7, “Creating Classes.”
Creating Arrays
An array can be thought of as a list of values all placed under one heading (i.e., within one variable). Whereas a string might store a single thought, like something you need to purchase from the grocery store—kiwis, an array can be the entire shopping list: kiwis, cereal, milk, etc.
An array’s name abides by the same rules as any other variable: it may contain only letters, numbers, and underscores, and it cannot begin with a number or uppercase letter. Arrays can also be assigned values using the assignment operator. However, since arrays store multiple values, a slightly different syntax is used to assigning them:
numbers = [1, 2, 3] groceries = ['kiwis', 'cereal', 'milk']
The array’s elements, which is to say its values, are put between square brackets, each separated from the next by a comma.
Arrays can contain a mixture of types:
stuff = ['b', 39.4, 8, 'mayonnaise']
Arrays can also be created using %w or %W, followed by the values within matching delineators:
labels = %w{hot mild cold}
In this syntax, the %w indicates that white space separates the array’s elements, so commas between the values, and quotation marks around the strings are not necessary. This syntax is like creating strings using %q and %Q (like %Q, %W treats the values as if in a double-quoted string).
You can easily print an entire array using puts (Figure 4.1):
puts numbers puts groceries
Figure 4.1 The puts method will print out every value in an array, each on its own line.
If you’d like to print, or do anything with, just a single item from the array, refer to the element’s indexed position: where the item is found within the list. Arrays use numeric indexes, with the first item found at 0. Referring to specific elements uses the square brackets again, with the integer index value between them:
puts groceries[2] # "milk"
You can also change an element’s value using this syntax:
groceries[2] = 'soy milk'
Finally, Ruby has a neat feature where a negative number can be used to count backward from the end of an array. The number -1 refers to the last item in an array:
puts stuff[-1] # "mayonnaise" puts numbers[-1] # 3
The number -2 refers to the second to last element:
puts stuff[-2] # 8
And so on.
To create and use arrays:
Create an array of strings:
names = ['Jack', 'Kate', 'Charlie', → 'Claire']
The names array stores four strings, indexed from 0 to 3.
Create an array of floats:
grades = [3.6, 2.34, 2.84, 4.0, 3.03]
Print out a specific item in each array (Figure 4.2):
puts names[1] puts grades[-1]
Figure 4.2 Two arrays are created, and then individual elements from each are printed.
The second item in the names array is printed (because the first element is indexed at 0). Then the last item in the grades array is printed.
Replace one of the names and print out the array’s contents (Figure 4.3):
names[3] = 'John' puts names
Figure 4.3 Existing array elements can be altered by assigning them new values (compare the final name with that in Figure 4.1).
The first line replaces the value of the fourth element in the array with John. Then the entire array is printed out.