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.
The syntax of the to_a
is given below:
arr.to_a
arr: This is the array object that we want to convert.
It returns an array that is the same as arr
.
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}"
arr1
and arr2
.to_a
method on the arrays we created and store the results inside variables a
and b
.to_a
returns the same elements of the array.