Functions

Crystal Procs

Using Procs

Crystal procs create callable objects with Proc types.

Introduction to Crystal Procs

In Crystal, procs are objects that encapsulate blocks of code which can be stored in variables, passed as arguments, and executed later. They are similar to lambdas or anonymous functions found in other programming languages. Procs are useful when you need to pass around units of behavior as first-class citizens in your programs.

Creating a Proc

To define a proc in Crystal, you use the -> syntax followed by a block. Here's a simple example of creating a proc that adds two numbers:

Calling a Proc

Once you've defined a proc, you can call it using the call method. Continuing with the previous example, you can execute the add_proc like this:

Procs with Different Signatures

Procs can take any number of arguments and can return any type. The type signatures should match the intended use cases. Here is an example of a proc that takes no arguments and returns a string:

Using Procs as Arguments

Procs can be passed as arguments to other functions, allowing dynamic behavior in your programs. Here's a function that accepts a proc and uses it:

Conclusion

Crystal procs provide a powerful way to encapsulate behavior and pass it around in your applications. They offer flexibility and reusability, making your code more modular and expressive. Understanding and using procs effectively will greatly enhance your programming in Crystal.

Previous
Blocks