Ruby Examples > Return Values

#---Return Values---

the return keyword is used to explicitly exit a method and optionally send a value back to the caller.

Two ways to return from a function

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

What can a function return?

A Ruby function can return any valid Ruby object, including:

  • Primitive types (e.g., numbers, strings, booleans)
  • Collections (e.g., arrays, hashes)
  • Custom objects (e.g., instances of classes)
  • nil (if no value is explicitly returned)

#

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

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.

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

Best Practices

  • Use return explicitly only when you want to exit a method early or make the code more readable.
  • Rely on implicit return for methods where the last expression clearly represents the return value.

Next example: Blocks.