Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array in descending order? [duplicate]

Tags:

sorting

ruby

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.

like image 204
anurag Avatar asked Mar 07 '14 13:03

anurag


1 Answers

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)}
like image 72
Arup Rakshit Avatar answered Oct 05 '22 02:10

Arup Rakshit