Ruby reverse Method

Ruby reverse function with examples

Ruby has great support for array manipulations. The reverse method is one of the helpful methods for array in ruby. This function is used to reverse an input array directly.

One thing to keep in mind that the reverse method creates a new copy of the input array and reverses the copied array by keeping the original array as same as before.

Ruby reverse method

Where arr is the input array which elements will be reversed.
Returns valueReturns a new and reversed version of that input array by keeping the input array as same as before
ParametersThis array method does not accept any parameters

Example program-1:

arr1 = [1, 2, 3, 4, 5, 6, 7]
arr2 = ["a", "b", "c", "d", "e"]

# It doesn't affect on arr1 & arr2
# because it copies to new one

# Not works
puts "#{arr1}"
puts "#{arr2}"
# It works
puts "#{arr1.reverse}"
puts "#{arr2.reverse}"


[1, 2, 3, 4, 5, 6, 7]
["a", "b", "c", "d", "e"]
[7, 6, 5, 4, 3, 2, 1]
["e", "d", "c", "b", "a"]

Note: The first two lines of output the array is not reversed it is because, although we reversed the array by calling the reverse method but the original array is still the same as before. So if we would keep the reversed array into a new array then we could get the reversed array. See the example program-2 below.

The last two lines of output are reversed it is because we are directly showing the function in the puts statement.

Example program-2:

arr3 = [8, 9, 10, 11, 12]
arr4 = ["Mehrab", "Mohul", "Lina", "Anusha"]
arr5 = [1]

x = arr3.reverse
y = arr4.reverse
z = arr5.reverse

# Unchanged
puts "#{arr3}"
puts "#{arr4}"
puts "#{arr5}"

# Changes
puts "#{x}"
puts "#{y}"
puts "#{z}"


[8, 9, 10, 11, 12]
["Mehrab", "Mohul", "Lina", "Anusha"]
[12, 11, 10, 9, 8]
["Anusha", "Lina", "Mohul", "Mehrab"]

Note: the first three lines of output are not reversed because as we told the original array is not reversed actually. When the reverse method is applied it creates a new array with the reversed elements then we kept in into three new array variables called x, y & z. That’s why the x, y & z are reversed in the last three lines of output.

Posted in