#---Return Values---
the return
keyword is used to explicitly exit a method
and optionally send a value back to the caller.
1. Explicit return:
A method can return a value using the return
keyword.
def add(a, b)
return a + b
end
result = add(41, 1)
p result # => 42
2. Implicit return: If return is not explicitly used, the method will implicitly return the value of the last executed expression.
def off_by_one_multiply(a, b)
x = a + 1
y = b + 1
x * y
end
result = off_by_one_multiply(6, 5)
p result # => 42
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.
def different_returns
return 11 # Integer
return 'Hello' # String
return [1, 2, 3] # Array
return { key: 'value' } # Hash
return nil # Nil
end
Ruby methods can return multiple values using an array. The caller can then unpack the array into separate variables.
def multiple_values
return 1, 2, 3, 4
end
a, b, c, d = multiple_values
p a # => 1
p b # => 2
p c # => 3
p d # => 4
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?
a = multiple_values
p a # => [1, 2, 3, 4]
The last 2 return values are ignored here.
a, b = multiple_values
p a # => 1
p b # => 2
All items except the first one are collected into an array:
a, *b = multiple_values
p a # => 1
p b # => [2, 3, 4]
All items except the last one are collected into an array:
*a, b = multiple_values
p a # => [1, 2, 3]
p b # => 4
a, *b, c = multiple_values
p a # => 1
p b # => [2, 3, 4]
p c # => 4
return
explicitly only when you want to exit a
method early or make the code more readable.