07. Arrays and Iterators
Let's write a program that asks us to type in as many words as we want (one word per line, continuing until we just press Enter on an empty line), and then repeats the words back to us in alphabetical order? Try to write that program...
...
Did you do it? You probably had some trouble. How do you store all those words? You don't know how many there will be. You can't just create a bunch of variables (word1, word2, etc.), because the user might type more words than you expected.
We need a way to store a list of things, without knowing how many things there are. We need Arrays.
An array is just a list in your computer. Each slot in the list acts like a variable: you can see what object a particular slot points to, and you can make it point to a different object. Let's make an array:
[]
[5]
['Hello', 'Goodbye']
flavor = 'vanilla'
[89.9, flavor, [true, false]]
First we have an empty array, then an array with a single number, then one with two strings. Next, we have a simple variable assignment; then an array with three objects: a float, the variable flavor, and another array.
To help us find things in arrays, each slot is given an index number. Programmers (and most programming languages, including Ruby) start counting from zero, so the first slot in the array is slot zero.
names = ['Ada', 'Belle', 'Chris']
puts names
puts names[0]
puts names[1]
puts names[2]
puts names[3] # This is out of range.
Ada
Belle
Chris
Ada
Belle
Chris
nil
We see that puts names prints each name in the names array. Then we use names[0] to see what is in "slot zero", names[1] for "slot one", and so on. When we tried names[3], Ruby gave us nil. nil is Ruby's way of saying "nothing". When you try to access a slot that doesn't exist, you get nil.
The Method each
each allows us to do something for each object the array points to. If we want to say something nice about each language in an array, we'd do this:
languages = ['English', 'Norwegian', 'Ruby']
languages.each do |lang|
puts 'I like ' + lang + '!'
puts 'Don\'t you?'
end
puts 'And let\'s hear it for C++!'
puts '...'
I like English!
Don't you?
I like Norwegian!
Don't you?
I like Ruby!
Don't you?
And let's hear it for C++!
...
What happened here? languages.each is a method that acts like a loop. The code between do and end is executed for each item in the array. The part |lang| is how we give a name to the current object (the object each is pointing to at that moment). The first time, lang points to 'English', the second time to 'Norwegian', and so on.
This is called an Iterator. Iterators are like loops, but they are methods that act on lists of things.
More Array Methods
We've learned [], each, and length (which works on arrays just like on strings). We also have join, push, pop, and sort.
join takes an array of strings and joins them together into a single string:
foods = ['artichoke', 'brioche', 'caramel']
puts foods
puts
puts foods.to_s
puts
puts foods.join(', ')
puts
puts foods.join(' :) ') + ' 8)'
artichoke
brioche
caramel
["artichoke", "brioche", "caramel"]
artichoke, brioche, caramel
artichoke :) brioche :) caramel 8)
push and pop are opposites. push adds an object to the end of the array, and pop removes the last object from the array (and tells you what object it was).
favorites = []
favorites.push 'raindrops on roses'
favorites.push 'whiskers on kittens'
puts favorites[0]
puts favorites.last
puts favorites.length
puts favorites.pop
puts favorites
puts favorites.length
raindrops on roses
whiskers on kittens
2
whiskers on kittens
raindrops on roses
1
A Few Things to Try
- Write the program we asked for at the beginning of this chapter. Hint: there's a lovely method for arrays called
sort. Use it! - Try writing the above program without using the
sortmethod. A large part of programming is solving sorting problems. - Rewrite your Table of Contents program (from the chapter on methods). Start the program with an array holding all of the information for your Table of Contents (chapter names, page numbers, etc.). Then print it all out in a beautifully formatted loop.
Now that we've learned about arrays and iterators, we're ready to start writing our own methods!