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.

Download Free Ruby Ebook

While loops in ruby

Example

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.

1
2
3
4
5
6
7
8
9
#!/usr/bin/ruby

$i = 1
$max = 5

while $i < $max do
puts("Loop iteration #$i" )
$i +=1
end

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:

1
ruby example8.rb

Exercises

  1. How does a while loop differ from a for loop?