Open In App

How to sort an array in descending order in Ruby?

In this article, we will discuss how to sort an array in descending order in ruby. We can sort an array in descending order through different methods ranging from using sort the method with a block  to using the reverse method after sorting in ascending order

Sort an array in descending order using the sort method with a block.

The sort method sorts the array in ascending order by default. By providing a custom block that compares elements in reverse order, the array can be sorted in descending order.

Syntax:

sort: array.sort { |a, b| b <=> a }

Example: In this example, we use sort method with a block that compares elements in reverse order (b <=> a) to sort the array in descending order

# Given array
array = [5, 2, 8, 1, 9]

# Sorting an array in descending order using the sort method with a block
sorted_array = array.sort { |a, b| b <=> a }
puts sorted_array # Output: Method 1 Output: [9, 8, 5, 2, 1]

Output
9
8
5
2
1

Sort an array in descending order using sort_by method with a block.

The sort_by method sorts the array based on the values returned by the block. By negating the values returned by the block, the array can be sorted in descending order.

Syntax:

sort_by: array.sort_by { |item| -item }

Example: In this example, we use sort_by method with a block that returns the negation of each element to sort the array in descending order.

 # Given array
array = [5, 2, 8, 1, 9]

 
# Sorting an array in descending order using the sort_by method with a block
sorted_array = array.sort_by { |item| -item }
puts sorted_array # Output: Output: [9, 8, 5, 2, 1]

Output
9
8
5
2
1

Sort an array in descending order using reverse method after sorting in ascending order.

In this method we first sort the array in ascending order using sort or sort_by, then reverses the order of elements,thus converting them in descending order. .

Syntax:

reverse: array.sort.reverse

Example: In this example we use sort to sort the array in ascending order and then reverses it using the reverse method to achieve descending order.

# Given array
array = [5, 2, 8, 1, 9]

 
# Sorting an array in descending order using the reverse method after sorting in ascending order
sorted_array = array.sort.reverse
puts sorted_array #  Output: [9, 8, 5, 2, 1]

Output
9
8
5
2
1
Article Tags :