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?

0

2 Answers 2

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 }
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, that's a good trick!
+1 for typing faster than me :P
Performance wise this is better (and more semantic if you ask me): a.sort_by(&:length).reverse
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"]

2 Comments

sort_by(&:length).reverse will be both more readable and faster.
I agree, but that wasn't the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.