How to Return Multiple Values in Ruby?
Last Updated :
28 Mar, 2024
This article focuses on discussing the different ways to return multiple values in Ruby.
Using an Array
In this method, multiple values are packed into an array, which is then returned from the method.
Syntax:
return [value1, value2, …]
Example:
Below is the Ruby program to return multiple values using an array.
Ruby
def return_multiple_values
return [1, 2, 3]
end
# Usage
result = return_multiple_values
puts result[0] # Output: 1
puts result[1] # Output: 2
puts result[2] # Output: 3
Output:
Explanation:
In this example, we call the method which returns the array in the variable result
, individual elements of the array are accessed using array indexing (result[0]
, result[1]
, result[2]
), and then printed.
Using a Hash
In this method, multiple values packed into a hash with keys representing the values, and then the hash is returned from the method
Syntax:
return { key1: value1, key2: value2, … }
Example:
Below is the Ruby program to return multiple values using a hash.
Ruby
def return_multiple_values
return { :a => 1, :b => 2, :c => 3 }
end
# Usage
result = return_multiple_values
puts result[:a] # Output: 1
puts result[:b] # Output: 2
puts result[:c] # Output: 3
Output:
Explanation:
In this example return_multiple_values
method returns a hash {:a => 1, :b => 2, :c => 3}
, where keys represent values. After which we store the returned hash in the variable result
,and access the individual values using hash keys (:a
, :b
, :c
), and then printed.
Using Parallel Assignment
In this method multiple values are returned separately from the method, allowing them to be assigned to multiple variables using parallel assignment.
Syntax:
return value1, value2
Example:
Below is the Ruby program to return multiple values using parallel assignment.
Ruby
def return_multiple_values
return 1, 2, 3
end
# Usage
a, b, c = return_multiple_values
puts a # Output: 1
puts b # Output: 2
puts c # Output: 3
Output:
Explanation:
In this example return_multiple_values method returns three values separately (1, 2, 3) . After which we store the returned values are assigned to variables a
, b
, and c
using parallel assignment. Then, each variable is printed.
Share your thoughts in the comments
Please Login to comment...