views:

82

answers:

1

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"]
+2  A: 

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?

sepp2k
@sepp2k: yes, right. Thank you....
Radek
To take DRY to its crazy limits, I'd consider: sort_by { |a| [2, 0, 1].collect { |i| a[i] } }
Wayne Conrad
I love ruby one can do magic with it if one knows how ....
Radek
@Wayne Conrad: I have just used your dry solution.Great.I have my elements I want to sort by in an array so I can change the order and add anyone at any time without changing the code at all!!!!
Radek
@Radek, I wasn't even thinking of user-determined sort order when I added that comment. Nice job!
Wayne Conrad