Ruby按列排序.dat文件 [英] Ruby sorting a .dat file by column
本文介绍了Ruby按列排序.dat文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对红宝石很陌生.我正在尝试打开文件.dat并按第二列的降序排列.到目前为止,我已经能够打开文件并全部读取.有什么建议吗?非常感谢.
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.
文件:
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) }
这是一个非常基本的实现,要与较大的输入数据一起使用,应进行一些调整(使用正则表达式而不是String#split
,而不是创建一个新的字符串来写入文件,依此类推)
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).
这篇关于Ruby按列排序.dat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文