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.
def vals : {Int32, Int32}
return {3, 7}
end
Here’s how we use the function:
def main
# Here we use the 2 different return values from the
# call with multiple assignment.
a, b = vals
puts a
puts b
# If you only want a subset of the returned values,
# use the underscore _ as a placeholder.
_, c = vals
puts c
end
main
When you run this program, you’ll see:
$ crystal run multiple_return_values.cr
3
7
7
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.