Functions
Crystal Blocks
Using Blocks
Crystal blocks use do-end or {} for inline logic.
Introduction to Crystal Blocks
In Crystal, blocks are anonymous functions that can be passed to methods. They are commonly used to implement inline logic, allowing for concise and readable code. Blocks can be defined using either do-end
or curly braces {}
. The choice between the two often depends on stylistic preference and the length of the block.
Using do-end Blocks
The do-end
syntax is typically used for multi-line blocks. It enhances readability and is preferred when the logic spans several lines. Here is an example of a do-end
block used with an array iteration:
Using {} Blocks
The curly braces {}
syntax is often used for single-line blocks. This makes the code more concise and is convenient for simple operations. Here is an example:
Passing Blocks to Methods
Blocks can be explicitly passed to methods in Crystal. When defining a method that takes a block, you can use the &block
parameter. Here’s how a method can be defined to accept a block:
Yielding to Blocks
The yield
keyword is used within a method to execute the passed block. It allows the block to be called from within the method's context:
Conclusion
Blocks in Crystal provide a flexible way to encapsulate logic that can be passed around and executed in different contexts. Whether using do-end
for multi-line logic or curly braces for one-liners, blocks enhance the expressiveness of Crystal code. Understanding how to define and use blocks is essential for writing clean and effective Crystal programs.
Functions
- Previous
- Default Arguments
- Next
- Procs