What is array.reverse() in Ruby?

In Ruby, array.reverse() is a method that reverses an array but does not change the original array. Instead, it returns a new array that contains the original array’s elements in reverse order.

The array.reverse() function

Syntax

array.reverse()

Parameters

This method does not take any parameters. It only requires the array instance.

Return value

The reverse() method returns a new array that contains the elements of the instance array in reverse order.

# creating array instances
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Javascript", "Python", "Java", "C++", "Ruby"]
# printing their reverse form using `reverse()` method
puts "#{array1} in reverse = #{array1.reverse()}"
puts "#{array2} in reverse = #{array2.reverse()}"
puts "#{array3} in reverse = #{array3.reverse()}"

Note: The reverse() method does not overwrite or change the original array.

array = [1, 2, 3, 4, 5]
reversedArray = array.reverse()
puts "#{reversedArray}\n"
puts "#{array}\n"

In the above code, we see that the original array remains the same.

Free Resources