This chapter is from the book

This chapter is from the book

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).

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: