Loops – repeating things
In why's legendary Ruby book two cartoon foxes keep shouting: “Chunky Bacon!” – repetition is delightfully easy in Ruby:
3.times do
puts "Chunky Bacon!"
endThe code between do and end is called a block and runs three times here. (The => 3 below is the value of 3.times itself.) With a counter it looks like this:
3.times do |i|
puts "Strip number #{i + 1}"
endThe |i| is a block parameter: on every round Ruby puts the current number into it – starting at 0, hence the + 1. For short blocks people usually write curly braces instead of do … end; it means exactly the same: 3.times { |i| puts i }.
Next to ▶ this cell has ⏯ Step through: watch the loop go round by round, and see what i is each time.
For counting there are ranges: 1..5 are the numbers from 1 to 5. each walks through all of them:
(1..5).each { |number| puts "#{number} times #{number} is #{number * number}" }With two dots the end is included, with three it is not: 1...5 only goes up to 4. If you'd rather count in words, use upto, downto or step:
1.upto(3) { |i| puts "up: #{i}" }
3.downto(1) { |i| puts "down: #{i}" }
0.step(10, 5) { |i| puts "in steps of five: #{i}" }Sometimes you don't know in advance how often something should run. That's what while is for: it repeats as long as the condition holds. Make sure it turns false at some point – or the loop runs forever. (⚡ Live stops such an endless loop after a second, ▶ does not – then only a reload helps.)
bacon = 10
bites = 0
while bacon > 0
bacon -= 3
bites += 1
end
"#{bites} bites, and the bacon is gone"In any loop, break leaves the loop at once, and next jumps straight to the next round. And often you need no loop at all: Ruby can do many things directly – (1..100).sum adds up all the numbers from 1 to 100.
(1..10).each do |i|
next if i.odd? # skip odd numbers
break if i > 6 # stop from 7 on
puts i
end
(1..100).sumChunky Bacon! exactly five times – with a loop, not with five puts lines.# 5 times Chunky Bacon, please!
bacon instead of every number divisible by 3, egg instead of every one divisible by 5, and bacon-egg when both apply. The remainder tells you whether a number divides: 9 % 3 is 0.# 1 to 15: "bacon" for multiples of 3, "egg" for multiples of 5,
# "bacon-egg" for both, the number itself otherwise - one per line