How do I sort a 2D array by the length of its inner elements? The number of inner elements is not the same.
Example:
a = [[1], [2, 3], [4, 5, 6, 7], [8,
This solution works:
a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort_by! { |array| -array.length }
#=> [[4, 5, 6, 7], [8, 9], [2, 3], [1]]
I am using the sort_by method and sort by length from largest to smallest.
This solution is more readable and works as well, but it is a bit slower:
a = [[1], [2, 3], [4, 5, 6, 7], [8, 9]]
a.sort_by(&:length).reverse!
#=> [[4, 5, 6, 7], [8, 9], [2, 3], [1]]
I am using the sort_by method using length, which will sort the array from smallest to largest by length. Then I use the reverse! method it to have it in order from largest to smallest.