Introduction To Ruby

The while statement is used to execute a chunk of code while a certain condition remains true. We call this a condition-controlled loop.

Example 1

# while

x = 1
while x<=10 do
  puts x
  x = x + 1


Notice that we use indentation for the chunk of code inside the while loop. THe standard two-space indentation shows clearly which statements are being repeated.

The condition can also be referred to as the stopping condition. We have to make sure that the stopping condition can be met or our code will continue to loop infinitely.

Example 2

Remember from the earlier sections how Ruby allows all sorts of tricks to refactor code and make it more compact. Here is a shorter version of the first program.

# while 2

x = 0
puts x = x + 1 while x<10


Notice the minor change in the way that the condition is expressed.


  1. Change the example so that it counts backwards from 10 to 1.
  2. Write a program that outputs the 2 times table.
  3. Write a program that allows the user to enter the times tables they choose. Output the first 12 items in that times table. Make your output useful to the user.
  4. Write a program that allows the user to enter a series of numbers, entering 0 when they want to stop. Output the total and mean average of the numbers. Think carefully here. There is only one average, so calculate that once. You will need to set your total to 0 before the loop and add each number the user enters to it. You will also need to keep a count of the how many numbers were entered. Set this to 0 before the loop too. After the loop has finished, calculate the mean average.