Ruby While and Until Loops

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

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

If computers do one thing well it is performing tasks very quickly. One thing computers do even better is performing the same task over and over again until specific criteria are met (or even infinitely if that is what is required). One this that computers are very bad at, however, is doing anything without being told to do it. Given these facts, it should come as no surprise that just about every programming language, Ruby included, provide mechanisms for instructing a computer system to repeat tasks.

In this chapter of Ruby Essentials we will look the structures provided by Ruby to allow loops to be built into applications.

The Ruby While Loop

The Ruby while loop is designed to repeat a task until a particular expression is evaluated to be false. The syntax of a while loop is as follows:

while expression do

... ruby code here ...

end


In the above outline, expression is a Ruby expression which must evaluate to true or false. The ruby code here marker is where the code to executed is placed. This code will be repeatedly executed until the expression evaluates to false.

For example, we might want to loop until a variable reaches a particular value:

i = 0
while i < 5 do
   puts i
   i += 1
end

The above code will output the value of i until i is no longer less than 5, resulting in the following output:

0
1
2
3
4

The do in this case is actually optional. The following is perfectly valid:

i = 0
while i < 5
   puts i
   i += 1
end

Breaking from While Loops

It is sometimes necessary to break out of a while loop before the while expression evaluates to true. This can be achieved using the break if statement:

i = 0
while i < 5
   puts i
   i += 1
   break if i == 2
end

The above loop when now exit when i equals 2, instead of when i reaches 5.


unless and until

Ruby's until statement differs from while in that it loops until a true condition is met. For example:

i = 0
until i == 4
   puts i
   i += 1
end

resulting in the following output:

0
1
2
3
4

The until keyword can also be used as a statement modifier, as follows:

puts i += 1 until i == 5

The unless statement provides an alternative mechanism to the if else construct. For example we might write an if else statement as follows:

if i < 10
   puts "Student failed"
else
   puts "Student passed"
end

The unless construct inverts this:

unless i >= 10
    puts "Student failed"
else
    puts "Student passed"
end