ruby - Sort Array of Arrays by length with tiebreaker -
i have array of arrays want sort longest length shortest. achieved enough sort_by
> = [ [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 want, have sort of tie-breaker lists of equal length. if 2 lists' lengths equal, list last entry greater should come first. in above, [1, 2, 9] , [1, 2, 3] should switched.
i don't care abouth case 2 lists have both equal length , equal last element, can in whatever order if occurs. don't know if/how can acheive ruby built-in sorting.
you can still sort_by, need realize ruby arrays compare element-by-element:
ary <=> other_ary → -1, 0, +1 or nil
[...]
each object in each array compared (using <=> operator).
arrays compared in “element-wise” manner; first 2 elements not equal determine return value whole comparison.
that means can use arrays sort_by key, throw in bit of integer negation reverse sort order , get:
a.sort_by { |e| [-e.length, -e.last] } that give [[4, 5, 6, 7], [1, 2, 9], [1, 2, 3]] you're looking for.
if you're not using numbers "negation reverse order" trick won't work, use shaunak's sort approach.
Comments
Post a Comment