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 arraysarr1 = [1, 2, 3, 4, 5]arr2 = ["a", "b", "c", "d", "e"]# call to_a on the arraysa = arr1.to_ab = arr2.to_a# print the returned valuesputs "#{a}"puts "#{b}"
Explanation
- Lines 2-3: We create two arrays,
arr1andarr2. - Lines 6-7: We call the
to_amethod on the arrays we created and store the results inside variablesaandb. - Lines 10-11: We print the results to the console.
As we have seen above, the
to_areturns the same elements of the array.