10

Possible Duplicate:
Sorting an array in descending order in Ruby

I want to sort an array of elements based on some condition, except in reverse order. So basically whatever it would have done and then reversed.

So for example I have an array of strings and I want to sort it by decreasing string length

a = ["test", "test2", "s"]
a.sort_by!{|str| str.length}.reverse!

While this does the job...is there a way to specify the condition such that the sorting algorithm will do it in reverse?

Community
  • 1
  • 1
MxLDevs
  • 19,048
  • 36
  • 123
  • 194

2 Answers2

26

The length is a number so you can simply negate it to reverse the order:

a.sort_by! { |s| -s.length }

If you're sorting on something that isn't easily negated then you can use sort! and manually reverse the comparison. For example, normally you'd do this:

# shortest to longest
a.sort! { |a,b| a.length <=> b.length }

but you can swap the order to reverse the sorting:

# longest to shortest
a.sort! { |a,b| b.length <=> a.length }
mu is too short
  • 426,620
  • 70
  • 833
  • 800
8

The answer from @mu is too short is great, but only works for numbers. For the general case, you can resort to the sort method:

 irb> a = ["foo", "foobar", "test"]
  => ["foo", "foobar", "test"]
 irb> a.sort{|a,b| a.length <=> b.length}
 => ["foo", "test", "foobar"]
 irb> a.sort{|a,b| b.length <=> a.length}
 => ["foobar", "test", "foo"]
Thilo
  • 17,565
  • 5
  • 68
  • 84