|
|
the |
|
Two ways to return from a function |
|
1. Explicit return:
A method can return a value using the |
|
|
|
2. Implicit return: If return is not explicitly used, the method will implicitly return the value of the last executed expression. |
|
|
|
What can a function return? |
|
A Ruby function can return any valid Ruby object, including:
|
|
Note: Only one value is returned at a time. Once return is executed, the method exits immediately. |
|
Returning multiple values from a function |
|
Ruby methods can return multiple values using an array. The caller can then unpack the array into separate variables. |
|
|
|
Array Destructuring: |
|
Now, what if the number of variables on the left side don’t match the number of values returned by the function on the right side? |
|
|
|
The last 2 return values are ignored here. |
|
All items except the first one are collected into an array: |
|
All items except the last one are collected into an array: |
|
|
|
Best Practices |
|
|
Next example: Blocks.