can't seem to write to a file properly

P

Peter Bailey

Hello,
Can someone help me diagnose what's going on with my script? Part of it
is below. I need to open a file, read its contents, do something to its
contents if a condition is true, then write new data to the end of the
contents, of the open file. It's doing it. It does add what I want it to
add, but, it adds it hundreds and hundreds of times, not just one time,
which is all I want.
...
Dir.glob("*.ps").each do |$psfile|
$filetime = File.ctime($psfile)
$filetime = $filetime.to_s.gsub!(/ -.*$/, "")
file_contents = File.read($psfile)
file_contents.scan(/\%\%Pages: (\d{1,5})[ ]+\n/) do #look for
pagecount in file
totalpages = $1 #put that count in
variable
end

if (totalpages.to_i % 2) !=0 then #if odd, then add
blank pg
totalpages = totalpages.to_i + 1
file_contents.gsub!(/.*$/, "\%\%Blank page for Asura.\n\%\%Page:
#{totalpages.to_i}\nshowpage\n")
end
File.open("#{$psfile}", "a") { |f| f.print file_contents }
end
...

Thanks.
 
A

Adam Shelly

Hello,
Can someone help me diagnose what's going on with my script?
....
it adds it hundreds and hundreds of times, not just one time,
which is all I want.
...

I think the problem is probably this line:
file_contents.gsub!(/.*$/, "\%\%Blank page for Asura.\n\%\%Page:
#{totalpages.to_i}\nshowpage\n")
You are replacing evevery single line in file_contents with the
"blank page" string
So you will add as many strings as you have lines in the original file.

If I understand what you are asking, I don't think you need the gsub
at all. If you want to append that string to the end, just do:

File.open("#{$psfile}", "a") { |f| f.print "\%\%Blank page for
Asura.\n\%\%Page:
#{totalpages.to_i}\nshowpage\n"}
 
P

Peter Bailey

Adam said:
I think the problem is probably this line:
file_contents.gsub!(/.*$/, "\%\%Blank page for Asura.\n\%\%Page:
#{totalpages.to_i}\nshowpage\n")
You are replacing evevery single line in file_contents with the
"blank page" string
So you will add as many strings as you have lines in the original file.

If I understand what you are asking, I don't think you need the gsub
at all. If you want to append that string to the end, just do:

File.open("#{$psfile}", "a") { |f| f.print "\%\%Blank page for
Asura.\n\%\%Page:
#{totalpages.to_i}\nshowpage\n"}

Great. Thanks, Adam. As often happens, I was making my life complicated.
I was using gsub! because someone suggested it instead of <<, which I
had been using. But, this is much better. Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top