To sort an array in ruby, you can use the sort
method. By default, the sort method sorts the array in ascending order.
main.rb86 chars5 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.rb200 chars8 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