-1

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.

user513951
  • 12,445
  • 7
  • 65
  • 82

2 Answers2

3
> 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]
Hetal Khunti
  • 787
  • 1
  • 9
  • 23
1

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}
Darkmouse
  • 1,941
  • 4
  • 28
  • 52