Multiple Return Values in Ruby

Ruby supports multiple return values, which is a feature often used to return both result and error values from a method.

# The method signature doesn't need to explicitly state
# the number of return values in Ruby
def vals
  return 3, 7
end

# In the main part of our script
# Here we use the 2 different return values from the
# method call with multiple assignment
a, b = vals()
puts a
puts b

# If you only want a subset of the returned values,
# you can use the underscore (_) as a placeholder
_, c = vals()
puts c

To run the script, save it as multiple_return_values.rb and use the ruby command:

$ ruby multiple_return_values.rb
3
7
7

In Ruby, methods can return multiple values without explicitly declaring it in the method signature. When calling such a method, you can use multiple assignment to capture all the returned values or use the underscore (_) to ignore specific values.

This feature in Ruby is similar to the multiple return values in other languages, allowing for more expressive and concise code, especially when dealing with methods that need to return more than one piece of information.

Next, we’ll look at how Ruby handles methods with a variable number of arguments, which is another powerful feature of the language.