What is to_a in Ruby?

Overview

The to_a method is called on an array in Ruby to return the same array. When it is called on an object, it converts the object to an array.

Syntax

The syntax of the to_a is given below:

arr.to_a

Parameters

arr: This is the array object that we want to convert.

Return value

It returns an array that is the same as arr.

Example

In the example below, we will demonstrate the use of the to_a on arrays. We will see that the same array is returned.

# create arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = ["a", "b", "c", "d", "e"]
# call to_a on the arrays
a = arr1.to_a
b = arr2.to_a
# print the returned values
puts "#{a}"
puts "#{b}"

Explanation

  • Lines 2-3: We create two arrays, arr1 and arr2.
  • Lines 6-7: We call the to_a method on the arrays we created and store the results inside variables a and b.
  • Lines 10-11: We print the results to the console. As we have seen above, the to_a returns the same elements of the array.

Free Resources