Reputation: 155
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.
Upvotes: 9
Views: 23662
Reputation: 118299
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)}
Upvotes: 21