Changes

Jump to: navigation, search

Ruby While and Until Loops

1,759 bytes added, 16:15, 26 November 2007
The Ruby While Loop
== The Ruby While Loop ==
The Ruby ''while'' loop is designed to repeat a task until a particular expression is evaluated to be ''truefalse''. The syntax of a ''while'' loop is as follows:
while ''expression'' do
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:
 
<pre>
i = 0
while i < 5 do
puts i
i += 1
end
</pre>
 
The above code will output the value of i until i is no longer less than 5, resulting in the following output:
 
<pre>
0
1
2
3
4
</pre>
 
The ''do'' in this case is actually optional. The following is perfectly valid:
 
<pre>
i = 0
while i < 5
puts i
i += 1
end
</pre>
 
== 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:
 
<pre>
i = 0
while i < 5
puts i
i += 1
break if i == 2
end
</pre>
 
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:
 
<pre>
i = 0
until i == 4
puts i
i += 1
end
</pre>
 
resulting in the following output:
 
<pre>
0
1
2
3
4
</pre>
 
The ''until'' keyword can also be used as a statement modifier, as follows:
 
<pre>
puts i += 1 until i == 5
</pre>
 
The ''unless'' statement provides an alternative mechanism to the ''if else'' construct. For example we might write an ''if else'' statement as follows:
 
<pre>
if i < 10
puts "Student failed"
else
puts "Student passed"
end
</pre>
 
The ''unless'' construct inverts this:
 
<pre>
unless i > 10
puts "Student failed"
else
puts "Student passed"
end
</pre>

Navigation menu