Forum: Ruby Why won't this "if" clause work properly?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Peter B. (Guest)
on 2006-05-20 00:24
Hi,
I'm going nuts with this tiny script. I'm basically just doing a page
count in a postscript print file. Even though I feed it jobs with an
even number of pages, it still carries through with line 15, which
should ONLY be run if it's an odd page count. When I do this in IRB, it
works fine. In other words, if its' an even page count, it exits, like
it should.
Thanks.


1 Dir.chdir("c:/scripts/ruby/temp/test")
2 fedpsfiles = Dir.glob('fed*.ps')
3 #an array for the page count
4 fedpsfiles.each do |fedpsfile|
5   #totalpages = []
6   #Read the whole file into memory.
7   contents = File.read(fedpsfile)
8   #Look for page entries and put them into an array.
9     totalpages = contents.scan(/^%%Page:.*[0-9]{1,5}$/) do
10    end
11  #If the totalpages.length, meaning the array count, is odd, then add
a blank
12  # at the end of the file.
13  remainder = totalpages.length.to_i % 2
14   if remainder == 1 then
15	contents << "%%Blank page for Asura.\nshowpage\n"
16       #Write the whole file now back to the original file.
17       File.open(fedpsfile, "w") { |f| f.print contents }
18     else exit
19   end
20 end
Pit C. (Guest)
on 2006-05-20 01:58
(Received via mailing list)
Peter B. schrieb:
> I'm going nuts with this tiny script.
> (...)

Peter, the problem with your script seems to be here:

> 9     totalpages = contents.scan(/^%%Page:.*[0-9]{1,5}$/) do
> 10    end

If you use String#scan with a block, the method returns the original
string ("contents" in this case). See

   http://www.ruby-doc.org/core/classes/String.html#M001884

Try to remove the "do end" part.

Regards,
Pit
Peter B. (Guest)
on 2006-05-20 03:03
Pit C. wrote:
> Peter B. schrieb:
>> I'm going nuts with this tiny script.
>> (...)
>
> Peter, the problem with your script seems to be here:
>
>> 9     totalpages = contents.scan(/^%%Page:.*[0-9]{1,5}$/) do
>> 10    end
>
> If you use String#scan with a block, the method returns the original
> string ("contents" in this case). See
>
>    http://www.ruby-doc.org/core/classes/String.html#M001884
>
> Try to remove the "do end" part.
>
> Regards,
> Pit

Thank you very, Pit. I believe the "do end" bit was in there from a
previous rendition of this attempt, but, now that you say it, yes, it
does make sense that it shouldn't be there. I'll try it first thing
Monday morning.
Cheers !
This topic is locked and can not be replied to.