Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort an array of arrays by three or more elements (ruby)

I have csv file with 14 columns and I want to sort it in ruby by 6th column then by 2nd and then by 11th column.

There is nice method .sort_by but it works only for two columns, doesn't it. And array_of_arrays.sort_by {|e| [e[2], e[0],e[1]],} doesn't work.

so let's say in the sample below I want it to be sorted by 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 is not as 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"]
like image 557
Radek Avatar asked Jan 22 '23 14:01

Radek


1 Answers

This:

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"]

That's what you want, right?

like image 146
sepp2k Avatar answered Jan 25 '23 11:01

sepp2k