anurag
anurag

Reputation: 155

How to sort an array in descending order?

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

Answers (2)

Arup Rakshit
Arup Rakshit

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

sidney
sidney

Reputation: 2714

You can do this:

[ 0,9,6,12,1].sort_by do |sort|
  -sort
end

Upvotes: 0

Related Questions