Sort Array of Arrays by length with tiebreaker
I have an Array of Arrays that I want to sort by longest length to
shortest. I achieved this easily enough with a sort_by
> a = [ [1, 2, 9],
[4, 5, 6, 7],
[1, 2, 3] ]
> a.sort_by(&:length).reverse # or a.sort_by {|e| e.length}.reverse
=> [[4, 5, 6, 7], [1, 2, 3], [1, 2, 9]]
What I want, however is to have a sort of tie-breaker for lists of equal
length. If two lists' lengths are equal, the list whose last entry is
greater should come first. So in the above, [1, 2, 9] and [1, 2, 3] should
be switched.
I don't care abouth the case where two lists have both equal length and
equal last element, they can be in whatever order if that occurs. I don't
know if/how I can acheive this with ruby built-in sorting.
No comments:
Post a Comment