Basics
Crystal Loops
Loop Structures
Crystal loops use while and each with break and next.
Introduction to Crystal Loops
Loops are fundamental in programming, allowing you to execute a block of code multiple times. In Crystal, loops are implemented using the while
method for conditional repetition and the each
method for iterating over collections. Additionally, controlling loop execution can be managed using break
and next
keywords. This guide will cover these loop structures in detail.
Using while Loops in Crystal
The while
loop in Crystal repeatedly executes a block of code as long as a specified condition is true. The condition is evaluated before the execution of the loop body, making it a pre-test loop.
In this example, the loop prints the value of count
until the condition count < 5
is false. The count += 1
increments the counter in each iteration.
Iterating with each
The each
method is used in Crystal for iterating over collections such as arrays or hashes. It provides an easy and effective way to access each element in a collection.
Here, the each
method iterates over the numbers
array, printing each element. The block variable number
represents the current element in each iteration.
Controlling Loop Execution with break
The break
keyword is used to exit a loop prematurely. This is useful when a condition is met that makes further iterations unnecessary.
In this example, the while
loop is infinite, but the break
keyword stops execution once count
equals 3.
Skipping Iterations with next
The next
keyword in Crystal is used to skip the current iteration and proceed to the next one. This can be useful for bypassing specific elements in a collection or avoiding certain conditions.
In this example, the next
keyword skips even numbers, so only odd numbers are printed.
Conclusion
Understanding and effectively using loops in Crystal is crucial for controlling flow and performing repetitive tasks. By mastering the while
and each
methods, along with break
and next
keywords, you can create efficient and readable Crystal programs.