To sort an array in Ruby, you can use the sort method.
In this example,
numbers
with values 5, 2, 8, 1, 6.sort
method to sort the array in ascending order.numbers
to the console.numbers = [5, 2, 8, 1, 6]
numbers.sort!
puts "Sorted array in ascending order: #{numbers}"
Sorted array in ascending order: [1, 2, 5, 6, 8]
In this example,
numbers
with values 5, 2, 8, 1, 6.sort
method with a block that sorts in descending order.numbers
to the console.numbers = [5, 2, 8, 1, 6]
numbers.sort! { |a, b| b <=> a }
puts "Sorted array in descending order: #{numbers}"
Sorted array in descending order: [8, 6, 5, 2, 1]
In this tutorial, we learned How to Sort an Array in Ruby language with well detailed examples.