I am very new to ruby. I am trying to open a file .dat and sort descending by the second column. So far I was able to open the file a read it all. Please any suggestions? thanks very much.
file:
1 88 59 74 53.8 0.00 280 9.6 270 17 1.6 93 23 1004.5 2 79 63 71 46.5 0.00 330 8.7 340 23 3.3 70 28 1004.5 3 77 55 66 39.6 0.00 350 5.0 350 9 2.8 59 24 1016.8 4 77 59 68 51.1 0.00 110 9.1 130 12 8.6 62 40 1021.1
output_lines = open("in.dat").lines.sort_by { |line| -line.split[1].to_i }
open("out.dat", "w") { |f| f.write(output_lines.join) }
This is a very basic implementation, to be used with large input data it should be tweaked a little bit (using a regexp instead of String#split, not creating a whole new string to write to the file, and so on).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With