sort an array in ruby

To sort an array in ruby, you can use the sort method. By default, the sort method sorts the array in ascending order.

main.rb
#sorting in ascending order
arr = [5, 1, 3, 2, 4]
arr.sort
#output => [1, 2, 3, 4, 5]
86 chars
5 lines

To sort the array in descending order, you can either use the sort method with a block or use the sort_by method.

main.rb
#sorting in descending order using sort with block
arr.sort { |a, b| b <=> a }
#output => [5, 4, 3, 2, 1]

#sorting in descending order using sort_by
arr.sort_by { |a| -a }
#output => [5, 4, 3, 2, 1]
200 chars
8 lines

In the above example, the block { |a, b| b <=> a } is used to sort the array in descending order. The <=> operator is used to compare the values in the array.

The sort_by method sorts the array based on the values returned by the block. In the example above, we pass -a to sort the array in descending order.

gistlibby LogSnag