Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - parsing a text file

Tags:

ruby

I am pretty new to Ruby and have been trying some really basic text parsing. I am now however trying to parse a little bit more of a complicated file and then push it out into a csv file (which I havent done before) and am getting quite stuck.

The file looks as follows,

Title
some text
some different text
Publisher: name
Published Date: date
Number1: number
Number2: number
Number3: number
Category: category
----------------------
Title
some text
some different text
Publisher: name
Published Date: date
Number1: number
Number2: number
Number3: number
Category: category
----------------------

etc.

Each line would represent a new "column" in the csv.

Would anyone please be able to lend a hand?

Thank you so much!

like image 672
kay85 Avatar asked Apr 03 '11 07:04

kay85


People also ask

What is parsing in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Syntax: DateTime.parse() Parameter: DateTime values. Return: given representation of date and time, and creates a DateTime object.

When opening a file What does the mode a mean Ruby?

"a+" Read-write, each write call appends data at end of file. Creates a new file for reading and writing if file does not exist. The following modes must be used separately, and along with one or more of the modes seen above. When the open mode of original IO is read only, the mode cannot be changed to be writable.


1 Answers

Here's a general idea for you to start with

File.open( thefile ).each do |line|
    print line without the new line if line does not contain  /--+/
    if line contains /--+/
        print line with a new line
    end
end
like image 72
kurumi Avatar answered Sep 21 '22 05:09

kurumi