On 4/19/05, Ghislain Mary <nospam / lunacymaze.org> wrote:
> Robert Klemme a ñÄrit :
> > You can do that easier:
> >
> > to_file.puts( /^caption:/ =~ line ? caption : line )
> >
> 
> In fact, I am doing several substitution, but I forgot to tell it.
> 
> >
> > Depends on your file's sizes.  If they are moderately sized you can slurp
> > the whole thing in, modify contents in mem with a single gsub and then
> > write them in one go.
> >
> 
> Thanks. Since the file can be quite large, I continue using something
> like before but with a Tempfile now. That gives something like:
> 
> require 'tempfile'
> require 'fileutils'
> include FileUtils
> 
> def clean_file(filename)
>    # Define the new caption
>    caption = "caption: my caption"
> 
>    # Process the content of the file
>    begin
>      tf = Tempfile.new(filename)
>      File.open(filename) do |from_file|
>        from_file.each do |line|
>          case
>            when line =~ /^caption:/: line.sub!($&, caption)
>            # Other substitutions...
>          end
>          tf.print line
>        end
>      end
>    ensure
>      tf.close unless tf.nil?
>    end
> 
>    # Replace the previous file with the new.
>    cp(tf.path, filename)
> end
> 
> But can't we open a file in read-write mode and directly do
> substitutions in it without using an auxiliary file?

You can do this, but only if you don't want to insert something inside
of the file, you can only overwrite parts of the file. So here is an
example:

File.open('test', 'w') { | f | f.print('This is a test') }
puts File.read('test')

File.open('test', 'r+') { | f | f.print('That') }
puts File.read('test')

File.open('test', 'r+') { | f | f.seek(5); f.print('was') }
puts File.read('test')

Output:
This is a test
That is a test
That wasa test

regards,

Brian

> 
> Ghislain
> 
> 


-- 
Brian Schröäer
http://ruby.brian-schroeder.de/