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?
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With