How to use an Explicit Return Statement In Ruby

The return the keyword is used to explicitly return the array, which contains both the array and the hash.

Syntax:

return [inner_array, inner_hash]

Example:

In this example, we create an array and a hash and then use return keyword to explicitly return an array containing both inner array and inner hash. The result of calling the method is stored in a variable result, and it’s printed.

Ruby
# Method to return an array containing an array and a hash
def return_array
  # Define an array
  inner_array = [1, 2, 3]

  # Define a hash
  inner_hash = { name: "John", age: 30 }

  # Return an array containing the array and hash
  return [inner_array, inner_hash]
end

# Call the method and store the result
result = return_array

# Print the result
p result

Output:

How to Return an Array that Contains an Array and Hash in Ruby Method?

In this article, we will learn how to return an array that contains an array and hash. We can return an array that contains an array and hash using the methods mentioned below:

Table of Content

  • Using an Explicit Return Statement
  • Using Implicit Return Statement
  • Using Array Literal and Hash Constructor

Similar Reads

Using an Explicit Return Statement

The return the keyword is used to explicitly return the array, which contains both the array and the hash....

Using Implicit Return Statement

Return statemnet is not used here instead we directly define and implicitly returns the array, allowing the last expression to be the return value....

Using Array Literal and Hash Constructor

the array and hash are directly constructed within the return statemen to return an array containing an inner array and a hash using literals....

Contact Us