Multiple Return Values in Crystal
Crystal has built-in support for multiple return values. This feature is used often in idiomatic Crystal, for example to return both result and error values from a function.
The {Int32, Int32}
in this function signature shows that the function returns 2 Int32
s.
Here’s how we use the function:
When you run this program, you’ll see:
In Crystal, you can return multiple values from a function by wrapping them in curly braces {}
, which creates a tuple. When calling such a function, you can use multiple assignment to easily capture all returned values, or use the underscore _
to ignore specific values.
This feature is particularly useful when you need to return multiple pieces of information from a function, such as a result and an error status, or when you want to return multiple processed values from a single operation.
Next, we’ll look at how Crystal handles functions with a variable number of arguments.