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
…
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”}
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”}
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.