views:

580

answers:

3

I am somewhat new to Ruby and I would appreciate some direction in solving the problem which I will now describe. I would like to write a Ruby program which can parse 3 separate text files each of which contain different delimiters and then sort them according to certain criteria.

Can someone please point me in the right direction?

+1  A: 

Enumerable#sort_by will allow you to sort an array (or other enumerable object) with a specific comparison function.

Jeffrey Aylesworth
+4  A: 

Not clear about what is the data format in your file and what criteria you used to sort ,I am not be able to provide you a acurate answer. However ,basically, you might need something like this:

File.open("file_name","r").read.split(",").sort_by {|x| x.length}

Explaination :

  • you opened a file using File.open
  • you read whole file and get a string , you can also read the file line by line using each method
  • you split the string use split , the delimite we used is ,
  • you use sort_by to sort them according to the criteria specified in the block
pierr
How does "r" get used here? What does it represent? Also, I don't quite understand what {|x| w.length} does. If you could please break this down a little more for a Ruby n00b such as myself, it would me much appreciated.
transmogrify
"r" represents that the file is being opened in "Read" mode. Also, w.lenth looks like a type. It should really be x.length.`{|x| x.length}` is a block passed to `sort_by` method. It makes the sort_by method sort by the length of each of the "split" words. Here, the word separator used is comma (,) in the `split` method.
Chirantan
I see now. Thank you very much for the clarification.
transmogrify
A: 

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 Hashes and Arrays, so you can use all the standard Ruby methods for sorting, filtering and iterating, including the aforementioned Enumerable#sort_by.

Jörg W Mittag
No, I meant regular .txt files not CSV files.
transmogrify