How to reverse an array permanently in Ruby

The reverse! method in Ruby can be used to permanently reverse an array. A similar method, reverse, only returns a copy of the reversed array but does not change the array permanently.

Syntax

array.reverse!

Parameter

This method does not take any parameters.

Return value

The original array is reversed and returned.

Code

In the example below, we create some arrays and demonstrate the use of reverse! to reverse the arrays permanently.

# 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!}"
# Confirm they are reversed permanently
puts "#{array1}" # [5, 4, 3, 2, 1]
puts "#{array2}" # ["e", "d", "c", "b", "a"]
puts "#{array3}" # ["Ruby", "C++", "Java", "Python", "Javascript"]

In the code above, from lines 13 to 16, we see that the arrays were permanently reversed after calling the reverse! method.

Free Resources