I would like to write a Ruby program which can pa开发者_如何学JAVArse three separate text files, each containing different delimiters, then sort them according to certain criteria.
Can someone please point me in the right direction?
It is not clear what is the data format in your files, and what criteria you used to sort, so I am not able to provide you a accurate answer.
However, basically, you might need something like this:
File.open("file_name","r").read.split(",").sort_by {|x| x.length}
You:
- Opened a file using
File.open
. - Read the whole file and got a string. You can also read the file line-by-line using the
each
method. - Split the string use
split
. The delimiter used is,
. - Use
sort_by
to sort them according to the criteria specified in the block.
Enumerable#sort_by will allow you to sort an array (or other enumerable object) with a specific comparison function.
If by "text files with delimiters" you mean CSV files (character seperated values), then you can use the csv
library, which is part of the standard library, to parse them. CSV gives you objects that look and feel like Ruby Hash
es and Array
s, so you can use all the standard Ruby methods for sorting, filtering and iterating, including the aforementioned Enumerable#sort_by
.
精彩评论