Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby sort array on condition in reverse order [duplicate]

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?

like image 429
MxLDevs Avatar asked Nov 04 '12 20:11

MxLDevs


1 Answers

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 }
like image 133
mu is too short Avatar answered Nov 10 '22 05:11

mu is too short