Array reverse() vs reverse! in Ruby


In this article, we will explore the two most widely used methods on arrays in Ruby. These are the reverse() method and the reverse! method.

reverse() method

The reverse() method in Ruby reverses the content of the array and returns a new array. Now, let's take a couple of examples to understand how it works.

Example 1

# reverse() method in Ruby

# array declaration
first_arr = [18, 22, 33, nil, 7, 6]

# array declaration
second_arr = [1, 5, 1, 3, 88, 9]

# array declaration
third_arr = [18, 22, 55, 6]

# reverse method example
puts "reversed array : #{first_arr.reverse()}

" puts "reversed array : #{second_arr.reverse()}

" puts "reversed array : #{third_arr.reverse()}

"

Output

reversed array : [6, 7, nil, 33, 22, 18]
reversed array : [9, 88, 3, 1, 5, 1]
reversed array : [6, 55, 22, 18]

Example 2

Let's explore one more example of the same reverse method.

# reverse() method in Ruby

# array declaration
first_arr = ["abc", "nil", "dog"]

# array declaration
second_arr = ["buffalo", nil]

# array declaration
third_arr = ["snake", nil, "dog"]

# reverse method example
puts "reversed array : #{first_arr.reverse()}

" puts "reversed array : #{second_arr.reverse()}

" puts "reversed array : #{third_arr.reverse()}

"

Output

reversed array : ["dog", "nil", "abc"]
reversed array : [nil, "buffalo"]
reversed array : ["dog", nil, "snake"]

reverse! Function

The reverse! function is used when we want to reverse the input array content into the same array. Let's explore an example of the reverse! function.

Example 3

# arrays of elements
arr1 = ["a", "b", "c", "d"]
arr2 = []
arr3 = [1]
arr4 = ["Javed", "Raju","Pruthvi"]

# reverse!
A = arr1.reverse!
B = arr2.reverse!
C = arr3.reverse!
D = arr4.reverse!

# Printing the same input array
# with reversed elements
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"

Output

["d", "c", "b", "a"]
[]
[1]
["Pruthvi", "Raju", "Javed"]

Updated on: 25-Jan-2022

696 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements