ruby can repeat a code block with a while loop. The while loop repeats code until a condition is true.
While loops are used when you are not sure how long code should be repeated.
A practical example: Think of a tv that should continue its function until a user presses the off button. Video game that should keep running until the user stops.
The program below is an example of a while loop in ruby.
It will repeat until a condition is true, which could be forever.
The code block can contain anything, from statements to function calls.
$i = 1
$max = 5
while $i < $max do
puts("Loop iteration #$i" )
In the example it repeats the code block until variable i is greater than max.
You must always increment the iterator (i), otherwise the while loop repeats forever.
The code block can be as many lines as you want, in this example its just one line of code that gets repeated.
Save as example8.rb. Then start with:
- How does a while loop differ from a for loop?