Learn/Ruby/5. Loops
Lesson 5 of 8
Sign in

Ruby, lesson 5

Loops

Computers are good at doing the same thing many times without getting bored. Ruby has a few ways to repeat code. Most of them are methods that take a block: a chunk of code between do ... end (or { ... } on one line) that the method runs for you.

Counting loops

When you know how many times to repeat, ask an integer to do it:

The name between the bars, |i|, is the block parameter. times counts from 0, so the values are 0, 1 and 2.

To count between two specific numbers, use a range with each, or upto and downto:

1..5 includes 5. With three dots, 1...5 stops 5.

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Savings goal

Press Ctrl Enter or Check to test your code.

before

Ruby also has a for n in 1..5 loop, but it is rarely used in modern code. The block style is the idiomatic choice.

while and until

When you do not know in advance how many times to loop, use while. It checks its condition before every pass and stops once the condition is false. until is the mirror image: it keeps going while the condition is false.

Make sure something inside the loop moves you toward the end. A condition that never becomes false gives you an infinite loop.

Reading until the input ends

gets returns nil when there is nothing left to read, and nil is falsy. That makes this pattern a neat way to process every line of input:

The parentheses around the assignment tell readers (and Ruby) that you meant =, not ==.

Leaving early: break and next

  • break stops the loop immediately and carries on after it.
  • next skips the rest of this pass and jumps to the next one.

For a loop with no natural condition, Ruby has loop do ... end, which runs forever until you break out of it.

gets&.chomp uses the safe navigation operator &.: if gets returns nil, the whole expression is nil instead of crashing with an error.

Further reading

  • Ruby docs: Control expressions (while, until, break, next)
  • Ruby docs: Integer (times, upto, downto)
  • Ruby docs: Range

Read a number n and print its times table from 1 to 10, one line each, in the form n x i = result. For the input 7 the first lines are:

and the last line is 7 x 10 = 70.

You are saving up for a bike. The first line of input is your goal in dollars. Every line after that is one deposit. Add the deposits in order and stop as soon as the total reaches or passes the goal, then print:

If the input runs out before you reach the goal, print how much is still missing instead:

For the input below the output is Goal reached on deposit 3 (40 + 30 + 50 = 120). The deposit of 10 is never read.

3.times { puts "Hip hip hooray!" }

3.times do |i|
  puts "Round #{i}"        # Round 0, Round 1, Round 2
end
(1..5).each { |n| print n, " " }     # 1 2 3 4 5
puts
10.downto(8) { |n| puts n }           # 10, 9, 8
1.step(10, 3) { |n| print n, " " }    # 1 4 7 10
cookies = 10
while cookies > 0
  puts "Eating... #{cookies} left"
  cookies -= 3
end
total = 0
while (line = gets)
  total += line.to_i
end
puts total
(1..10).each do |n|
  next if n.even?          # skip even numbers
  break if n > 7           # stop completely after 7
  puts n                   # 1, 3, 5, 7
end
loop do
  answer = gets&.chomp
  break if answer.nil? || answer == "quit"
  puts "You said #{answer}"
end
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
Goal reached on deposit 3
Still short by 25
100
40
30
50
10