I have an array:
a = [ 0,9,6,12,1]
I need a way to sort it in descending order:
a = [12,9,6,1,0]
For sorting in ascending order I have a Ruby function a[].to_a.sort
,
I'm looking for a function to sort the array in descending order.
do as below
a = [ 0,9,6,12,1]
sorted_ary = a.sort_by { |number| -number }
# or
sorted_ary = a.sort.reverse
update
Another good way to do this :
a.sort {|x,y| -(x <=> y)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With