To sort an array in descending order in Ruby, you can use the `sort` method with a custom block.
In this example,
numbers
.sort
method with a custom block to sort the array of integers in descending order.numbers = [5, 2, 8, 1, 9]
numbers.sort! { |a, b| b <=> a }
puts "Sorted array in descending order: #{numbers}"
Sorted array in descending order: [9, 8, 5, 2, 1]
In this example,
words
.sort
method with a custom block to sort the array of strings in descending order.words = ["apple", "banana", "cherry", "date"]
words.sort! { |a, b| b <=> a }
puts "Sorted array in descending order: #{words}"
Sorted array in descending order: ["date", "cherry", "banana", "apple"]
In this tutorial, we learned How to Sort an Array in Descending Order in Ruby language with well detailed examples.