published: 29th of July 2021
Crystal has a set of looping structures similar to what can be found in other languages.
An each loop is similar to a for loop in other languages.
# 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 allows you to iterate for N number of iterations.
# Exampe times block.
10.times do
puts "Show me your stuff"
end
while and loop have similar behaviour and start an infinite loop. It is up to the user to program the exit condition.
# 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
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/syntax_and_semantics/while.html