How to sort an array of arrays with three or more elements (ruby)

I have a csv file with 14 columns, and I want to sort it in ruby ​​on the 6th column, and then on the 2nd and then on the 11th column.

There is a good .sort_by method, but it only works for two columns, right. And array_of_arrays.sort_by {|e| [e[2], e[0],e[1]],}does not work.

so let's say in the example below, I want it to be sorted into 3rd, 1st, 2nd columns

array_of_arrays = [[1,9,'a'],[2,2,'a'], [2,6,'b'], [1,3,'a'], [2,1,'b']]

array_of_arrays.each {|line| puts line.inspect }
puts
array_of_arrays.sort_by {|e| [e[2], e[0]]} .each {|line| puts line.inspect }

but the result does not match the desired

[1, 9, "a"]
[2, 2, "a"]
[2, 6, "b"]
[1, 3, "a"]
[2, 1, "b"]

[1, 9, "a"]
[1, 3, "a"]
[2, 2, "a"]
[2, 6, "b"]
[2, 1, "b"]
+3
source share
1 answer

It:

array_of_arrays = [[1,9,'a'],[2,2,'a'], [2,6,'b'], [1,3,'a'], [2,1,'b']]

array_of_arrays.each {|line| p line }
puts
array_of_arrays.sort_by {|e| [e[2], e[0], e[1]]} .each {|line| p line }

Produces the following output for me:

[1, 3, "a"]
[1, 9, "a"]
[2, 2, "a"]
[2, 1, "b"]
[2, 6, "b"]

What do you want, right?

+8
source

Source: https://habr.com/ru/post/1731788/


All Articles