You are already familiar with a couple of Ruby classes (Integer and String). The class Array is used to represent a collection of items.

This is best seen through an example:

shell> irb --simple-prompt 
>> numbers = [ "zero", "one", "two", "three", "four" ]  
=> ["zero", "one", "two", "three", "four"]
>> numbers.class 
=> Array

Here the class method tells us that the variable numbers is an Array. You can access the individual elements of the array like this:

>> numbers[0] 
=> "zero"
>> numbers[1]
=> "one"
>> numbers[4]
=> "four"

You can add more entries to the array by simply typing:

>> numbers[5] = "five"
=> "five"

Notice that the entries in the array are stored sequentially, starting at 0. An array can contain any number of objects. The objects contained in the array can be manipulated just as before.

>> numbers[3].class
=> String
>> numbers[3].upcase
=> "THREE"
>> numbers[3].reverse 
=> "eerht"

Warning: Notice that Array’s start counting at 0, not 1

Other basic Array methods include Concatenation (+), Difference (-), Intersection (&), and Union (|):

>> numbers = [ "zero", "one", "two", "three", "four" ]  
=> ["zero", "one", "two", "three", "four"]
>> other_numbers = ["one", "five"]
=> ["one", "five"]
>> numbers + other_numbers
=> ["zero", "one", "two", "three", "four", "one", "five"]
>> numbers - other_numbers
=> ["zero", "two", "three", "four"]
>> numbers & other_numbers
=> ["one"]
>> numbers | other_numbers
=> ["zero", "one", "two", "three", "four", "five"]

You can use the join method to join the items in an array together into a string. Or use the split method on a string to create an array of items, like so:

>> numbers.reverse.join("... ") + "!"
=> four... three... two... one... zero!
>> "This is a sentence".split(" ")
=> ["This", "is", "a", "sentence"]

What kind of things can you put on arrays? Well, any object really. How about strings and integers?:

>> address = [ 284, "Silver Spring Rd" ]
=> [284, "Silver Spring Rd"]

Array of arrays

As we have seen, you can use square brackets to get at a particular element of an array. Square brackets are really just an alias for the method Array#slice. If the slice method returns another array, we can add another set of square brackets to then get at the contents of the inner array.

For example:

shell> irb --simple-prompt
>> array = [ ["a",1], ["b",2], ["c",3] ]
=> [["a", 1], ["b", 2], ["c", 3]]
>> array[1]
=> ["b", 2]
>> array[1][0]
=> "b"
>> array[1][1]
=> 2

Another way that we could write array\[1]\[0] would be array.slice(1).slice(0), but the second form is no fun to read.

Here is another example:

>> addresses = [ [ 284, "Silver Sprint Rd" ], [ 344, "Ontario Dr" ] ]
=> [[284, "Silver Sprint Rd"], [344, "Ontario Dr"]]
>> addresses[0]
=> [284, "Silver Sprint Rd"]
>> addresses[1]
=> [344, "Ontario Dr"]
>> addresses[0][0]
=> 284
>> addresses[0][1]
=> "Silver Sprint Rd"

Can you see why arrays are so cool?

Exercises