Robert Klemme
4/19/2005 2:26:00 PM
"Ghislain Mary" <nospam@lunacymaze.org> schrieb im Newsbeitrag
news:4264D003.4080500@lunacymaze.org...
> Robert Klemme a écrit :
> > 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
Another small remark: I'd refactor the actual replacement out of this
method into another method that receives two IO instances. That's more
modular and it makes testing easier (you can use StringIO).
> But can't we open a file in read-write mode and directly do
> substitutions in it without using an auxiliary file?
Yes, but this has the problems others have pointed out. This works only
good as long as substitutions have the same lenght as the original piece
they replace - a rather seldom scenario I figure.
Kind regards
robert