Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Control Flow and Methods

Loops, Ranges and Iteration

Repeat code in Crystal with while, until, loop, times, upto, step and each, plus inclusive and exclusive ranges, break, next, and the idiomatic iterator style with Ruby stand-ins.

Repeating work is where most programs spend their time. Crystal offers classic loops (while, until, loop) and, more idiomatically, iterator methods such as times, each, upto and step that take a block. Ranges describe sequences of values. This lesson shows all of them and explains why iterators are usually the better choice.

Crystal listings are read-only on this site. The Ruby stand-ins are runnable and use the same loop vocabulary; Crystal-specific differences are called out.

while and until

CRYSTAL
count = 3
while count > 0
  puts "count: #{count}"
  count -= 1
end
puts "liftoff"

This prints count: 3, count: 2, count: 1, then liftoff. until is the opposite: it runs while its condition is false.

CRYSTAL
n = 0
until n == 3
  puts n
  n += 1
end

Use while when you do not know how many iterations you will need, for example reading until the input ends.

loop with break

loop runs forever until you break:

CRYSTAL
attempts = 0
loop do
  attempts += 1
  puts "try #{attempts}"
  break if attempts == 3
end

break can carry a value, which becomes the value of the whole loop expression, and next skips to the next iteration:

CRYSTAL
found = loop do
  attempts += 1
  next if attempts.odd?
  break attempts if attempts > 6   # found == 8
end

An infinite loop is the usual shape of a server accept loop or a worker waiting for jobs.

times, upto, downto and step

Integers have methods that repeat a block, and they read like English:

CRYSTAL
3.times { |i| puts "i = #{i}" }         # 0, 1, 2
1.upto(3) { |i| puts i }                # 1, 2, 3
3.downto(1) { |i| puts i }              # 3, 2, 1
0.step(to: 10, by: 5) { |i| puts i }    # 0, 5, 10

These do not need a counter variable you could forget to update, and the compiler turns them into tight loops, so there is no speed penalty compared with while.

Ranges

A range is a sequence of values with a start and an end. There are two styles:

CRYSTAL
inclusive = 1..5      # 1, 2, 3, 4, 5
exclusive = 1...5     # 1, 2, 3, 4
letters   = 'a'..'e'

Ranges can be iterated, tested and converted:

CRYSTAL
(1..5).each { |n| print n, " " }       # 1 2 3 4 5
puts (1..5).sum                        # 15
puts (1..10).step(3).to_a              # [1, 4, 7, 10]
puts (1..5).includes?(3)               # true
puts (1...5).size                      # 4
puts ('a'..'e').to_a                   # ['a', 'b', 'c', 'd', 'e']
puts (1..5).reverse_each.to_a          # [5, 4, 3, 2, 1]

Ranges can also be open ended: (1..) starts at 1 and never ends, and (..10) has no start. Open ranges are handy for slicing (array[2..] means "from index 2 to the end") and in case.

Here is the Ruby stand-in. All of the loops and ranges below behave the same in Ruby, so you can run them and compare with the Crystal listings above:

Ruby Stand-in: loops and ranges in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

each and the iterator style

Collections and ranges have each, which hands every element to a block:

CRYSTAL
fruits = ["apple", "banana", "cherry"]

fruits.each { |fruit| puts fruit }

fruits.each_with_index do |fruit, i|
  puts "#{i + 1}. #{fruit}"
end

fruits.each.with_index(1) { |fruit, i| puts "#{i}: #{fruit}" }

Prefer these to manual index loops. There is no off-by-one risk and no out-of-range index. When you need a result and not only a side effect, use map, select and reduce, which have their own lesson in the collections chapter.

Crystal has no for loop. If you know Ruby's for x in list, replace it with list.each do |x|.

break, next and nested loops

Inside a block, next skips to the next element and break leaves the loop. To leave nested loops, use a flag or move the code into a method and return:

CRYSTAL
def find_pair(target : Int32) : {Int32, Int32}?
  (1..9).each do |a|
    (1..9).each do |b|
      return {a, b} if a * b == target
    end
  end
  nil
end

puts find_pair(42).inspect    # {6, 7}

return leaves the whole method, which is the cleanest way out of nested loops.

Ruby Stand-in: return from nested loops in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Loop variables and closures

Variables created inside a block are local to it and start fresh on each iteration. A variable declared before the loop and changed inside it keeps its value afterwards:

CRYSTAL
total = 0
(1..4).each { |n| total += n }
puts total    # 10

Choosing a loop

Need Use
Repeat N times n.times
Walk a collection each, each_with_index
Count up or down upto, downto, step
Unknown number of repeats while, loop + break
Build a new collection map, select (later lesson)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which loop statement does Crystal NOT have?

    Crystal has no for loop; use each, times, upto and friends instead.
  2. 2. What does (1...5).to_a give?

    Three dots exclude the end value.
  3. 3. What does break value do inside loop do?

    break can return a value, which becomes the value of the loop expression.
  4. 4. Which is the cleanest way to leave two nested loops at once?

    Put the loops in a method and return, or use a flag.

Summary

  • while and until repeat on a condition; loop do ... end repeats until break.
  • times, upto, downto, step and each replace counters and for loops.
  • a..b includes the end, a...b excludes it; ranges can be open-ended.
  • break can return a value and next skips an iteration.
  • Return from a method to escape nested loops.

Next: Methods and Arguments