Looping with for and the Ruby Looping Methods

From Techotopia
Revision as of 16:38, 26 November 2007 by Neil (Talk | contribs)

Jump to: navigation, search

In the previous chapter we looked at Ruby While and Until Loops as a way to repeat a task until a particular expression evaluated to true or false. In this chapter we will look at some other mechanisms for looping in a Ruby program, specifically for loops and a number of built-in methods designed for looping, specifically the loop, upto, downto and times methods.

The Ruby for Loop

The for loop is a classic looping construct that exists in numerous other programming and scripting languages. It allows a task to be repeated a specific number of times. Ruby differs in that it it used in conjunction with ranges (see Ruby Ranges for more details). For example, we can repeat a task 8 times using the following for statement:

for i in 1..8 do
    puts i
end

The above loop will result in the following output:

1
2
3
4
5
6
7
8

The do in the for statement is optional, unless the code is placed on a single line:

for i in 1..8 do puts i end

Ruby for loops can be nested:

for j in 1..5 do
     for i in 1..5 do
         print i,  " "
     end
puts
end


The above code will result in the following output:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Also, the break if statement can be used to break out of a for loop (note that only the inner for loop is exited, if the loop is nested the outer loop will continue the looping run):

for j in 1..5 do
     for i in 1..5 do
         print i,  " "
         break if i == 2
     end
end

resulting the the inner loop breaking each time i equal 2:

1 2
1 2
1 2
1 2
1 2