Crystal Notes: Loops
Published: 2021-07-29
Intro
Crystal has a set of looping structures similar to what can be found in other languages.
Each
An each loop is similar to a for loop in other languages.
crystal
# Example each loop.
stuff_and_things = ["stuff", "things"]
stuff_and_things.each do |item|
puts item
end
# Example each loop with an index.
stuff_and_things = ["stuff", "things"]
stuff_and_things.each_with_index do |item, idx|
puts "#{idx} - #{item}"
end
Times
times allows you to iterate for N number of iterations.
crystal
# Exampe times block.
10.times do
puts "Show me your stuff"
end
While/Loop
while and loop have similar behaviour and start an infinite loop. It is up to the user to program the exit condition.
crystal
# Example of while loop.
is_true = true
while is_true
puts "blah"
is_true = false
end
# Example of a loop...er loop.
# Usefull if you want a single iteration.
is_true = true
loop do
puts "blah"
break if is_true
end
Links
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/syntax_and_semantics/while.html