[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Newbie questions

Harold Hausman

12/11/2006 1:24:00 PM

On 12/11/06, Dav Jones <kakaze@talk21.com> wrote:
> Hello, I'm quite new to this whole Ruby malarky and I'm having some real
> trouble with more intermediate features.

malarky indeed.

>
> What I'm wanting to do is read a text file and then do some stuff to it.
> So...:
>
> 1: How do I use the 'source' command to read the file into somewhere
> usable?
> I'm wanting to do stuff to each line of the file individually once I
> have it.

IO.readlines is your friend:
http://ruby-doc.org/core/classes/IO.ht...

>
> 2: How do I apply a regular expression to the lines of the file?
>
>

#this is grossly inefficient and totally untested, but easy to read
output_file_lines = []
IO.readlines( 'sweetfile.txt' ) do |line|
output_file_lines.push( line.gsub( /old|bad|stuff/, 'New Good Stuff!' ) )
end

IO.open( 'sweeterfile.txt', 'w' ) do |file|
output_file_lines.each do |line|
file.puts( line )
end
end

hth,
-Harold