What does Array#reverse method in Ruby do?

176 views Asked by At

In Ruby, when I call reverse method on an array, it doesn't reverse sort the array completely.

array = [5, 4, 9, 8, 7, 1, 2]

array.reverse # => [2, 1, 7, 8, 9, 4, 5]

I'm unable to understand what operation it's performing on the array.

2

There are 2 answers

0
Hetal Khunti On BEST ANSWER
> array
 => [5, 4, 9, 8, 7, 1, 2] 
> array.sort.reverse  # it will sort the array by value in descending order
 => [9, 8, 7, 5, 4, 2, 1] 

Note:

  • sort : Returns a new array created by sorting self.
  • reverse : Returns a new array containing self‘s elements in reverse order.

See how it works:

> array.reverse   # it will reverse the array by indexing
 => [2, 1, 7, 8, 9, 4, 5] 
> array.sort  # it will sort the array by value in ascending order
 => [1, 2, 4, 5, 7, 8, 9]
0
Darkmouse On

Array#reverse reverses the order of an array, but does not sort the array in reverse order.

array = [1,5,7,3]
array.reverse
=> [3,7,5,1]

If you want to sort an array in reverse order, you could try this

array.sort_by{|a|array.max - a}