Repeating with loops

Run the same code many times without writing it many times.

Your Ruby code runs inside your browser tab. Nothing to install.

Counting with a loop

A loop runs the same block of code several times.

(1..3) is the run of numbers from 1 to 3. .each do |i| runs the block once for each of them, with the number in i. The block finishes at end.

The loop variable holds a different number on each pass.

Example
(1..3).each do |i|
  puts i
end

Your turn: counting

Count a little further than the example does.

Practice task

Use a loop to print the numbers from 1 to 5, one on each line.

Your answer is run and checked in the lesson. Create a free account to try it.

Building up a result

A loop is often used to build up one answer. Create a variable before the loop, change it inside the loop, and use it after the loop.

total += i is a short way to write total = total + i.

The print in the example comes after the loop has closed, so it runs once, at the end.

Example
total = 0
(1..4).each do |i|
  total += i
end
puts total

Repeating while something is true

A while loop repeats for as long as its condition is true, and finishes at end.

Something inside the loop must change so that the condition becomes false. If nothing does, the loop never ends.

The example halves a number until it drops below 10.

Example
n = 80
while n >= 10
  puts n
  n = n / 2
end

Your turn: a total

Combine a loop with a running total.

Practice task

Use a loop to add the numbers from 1 to 10, then print the total once.

Your answer is run and checked in the lesson. Create a free account to try it.