Chapter 12: Loops

Loops are another super useful control structure that lets you repeat a piece of code for a certain number of times, or until a condition is met.

Here’s the simplest example: Print something 5 times.

5.times do
  print 'a'  # aaaaa
end

A more common pattern is to repeat an action for all the elements of an array.

names = ['Taylor', 'David']

names.each do |name|
  puts "Hello, #{name}"
end

# Output
#
# Hello, Taylor
# Hello, David

If you want to repeat something while some condition is true, use the while loop.

number = 0

while (number < 10>)
  print number
  number += 1
end

# Output
0123456789

Break and Next

Often while a loop is running, you want to stop the computation and get out of the loop after a condition is met. Use the break statement for this.

num = 0

while num < 20
  print num
  break if num == 7
  num += 1
end

# Output
#
# 01234567

In contrast, sometimes you want to skip the rest of the computation inside the loop when a condition is met, and continue from the next iteration. Use the continue statement for this.

characters = ['a', 'b', 'c']
characters.each do |char|
  next if char == 'b'
  print char
end

# Output
# 
# ac

Next: Functions