(7 ratings)   
By: math.umd.edu
An iterator is a special kind of method. It is a method that lets you access items one at a time.
Added: 23 June 2008    Views: 106  
PathComputers    Programming    Ruby
Keywords: computers   programming   ruby   coder   code   language   iterators  
Do you like this tutorial? Now you can support our team to add more :     
 
 
 

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"]  
friends.each do |friend|
puts "I have a friend called " + friend
end

This will produce:

I have a friend called Melissa  
I have a friend called Jeff
I have a friend called Ashley
I have a friend called Rob

. 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|
puts num
end

Which will produce:

0
1
2
3

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"]  
friends.each do |friend|
puts "I have a friend called " + friend
end

Can also be written as:

# 'i' is a standard notation for 'index'.
4.times do |i|
puts "I have a friend called " + friends[i]
end

Now, here is something cool: Remember the Array#length method? How about?:

friends.length.times do |i|  # 'i' for 'index'.
puts "I have a friend called " + friends[i]
end

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|
# Print only even indices (i.e. remainder with 2 is 0).
if i % 2 == 0
puts "I have a friend called " + friends[i]
end
end

This produces:

I have a friend called Melissa  
I have a friend called Ashley

Now, say I want to print all my friends in alphabetical order:

friends.sort.each do |friend|
puts "I have a friend called " + friend
end

Which produces:

I have a friend called Ashley
I have a friend called Jeff
I have a friend called Melissa
I have a friend called Rob

Exercises

  1. Print all the contents of friends in reverse alphabetical order.

  2. Print the lyrics to "99 bottles of beer on the wall" using an iterator.

  3. Say I have the array:

    names = [ "daniel", "eduardo", "alejandro", "enrique" ]  

    Use String#capitalize to print these names capitalized.

About the Author :
math.umd.edu
Iterators In RUBY
Articles and Tutorials Directory by www.learnfobia.com
 Rate this tutorial : Rate 1Rate 2Rate 3Rate 4Rate 5
  |    Add to Favorites
  |    Send to Friend
  |    Print
Comments