How to use Array Literal and Hash Constructor In Ruby

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

Syntax:

[[array_value1, array_value2], {key1: “value 1”, key 2: value 2 }];

Example:

In this example both the array and hash are constructed using literals directly within the array.The result is stored in a variable result and printed.

Ruby
# Method to return an array containing an array and a hash
def return_array
  # Return an array containing an array and hash using literals
  [[1, 2, 3], { name: "John", age: 30 }]
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