



(7 ratings)
Now we get to one of the coolest features of Ruby: iterators .
An iterator is a special kind of method. It is a method that lets you access items one at a time.
Arrays are not the only objects that have iterators, but the are one of the most important. Iterators are best seen through an example. Here we use Array#each:
friends = ["Melissa", "Jeff", "Ashley", "Rob"] |
This will produce:
I have a friend called Melissa |
. The one with the form n.times do .... This is, in fact, an iterator. And it lets you iterate over the integers from 0 to n-1:
4.times do |num| |
Which will produce:
0 |
The fact, that this starts counting at 0 might seem odd. But it actually matches arrays (which start counting at 0). Thus, the code:
friends = ["Melissa", "Jeff", "Ashley", "Rob"] |
Can also be written as:
# 'i' is a standard notation for 'index'. |
Now, here is something cool: Remember the Array#length method? How about?:
friends.length.times do |i| # 'i' for 'index'. |
Now suppose that I don't want to print all my friends. I just want to print every other friend. We can just print out the friends that correspond to even numbered indices. We can do this with the remainder (Integer#%) method.
friends.length.times do |i| |
This produces:
I have a friend called Melissa |
Now, say I want to print all my friends in alphabetical order:
friends.sort.each do |friend| |
Which produces:
I have a friend called Ashley |
Exercises
Print all the contents of friends in reverse alphabetical order.
Print the lyrics to "99 bottles of beer on the wall" using an iterator.
Say I have the array:
names = [ "daniel", "eduardo", "alejandro", "enrique" ]
Use String#capitalize to print these names capitalized.
20 Random Tutorials from the same category :
Progress Bars with GD2 and Ruby
Printing the addressbook RUBY
Arrays In RUBY
Difference of Gtk+ and Ruby/Gtk
Writing iterators In RUBY
Implementing AddressBook In RUBY
Iterators In RUBY
What can ruby arrays do?
Classes and methods in RUBY
Sorting the addressbook RUBY
More features IN RUBY
Example: Addressbook RUBY
Hashes In RUBY
The Scalability of Ruby













