From: Peter Bailey Date: 2006-04-13T03:06:07+09:00 Subject: Re: Simple substitutions Ross Bamford wrote: > On Thu, 2006-04-13 at 00:24 +0900, Peter Bailey wrote: >> blanks.push($1) >> >> >> I'm getting this, which I'm extremely proud of, but, it doesn't quite >> make it: >> >> +++++++++++++++++++++++++++++++++++++++++ >> Blank Pages in This PDF: 46 68 72 80 83 >> No. of Blanks: #number >> +++++++++++++++++++++++++++++++++++++++++ > > You're almost there - I would make just a few small changes: > > blanks = [] > File.read("test2.ps").scan(/ ... your regexp ... /) do > blanks.push($1) > end > > unless blanks.empty? > File.open("psout2.txt", "w") do |out| > out << "Blank Pages in This PDF: #{blanks.join(' ')}\n" << > "No. of blanks: #{blanks.length}\n" > end > end > > The key points I changed being: > > * Rather than having an extra " " in the array for each > element (which would throw the length off, too), I use > Array#join to format for output. > > * I surround all expressions within strings with #{} - > prefixing with # alone works only for global variables > and is probably bad form - stick to #{var} as much as > possible. > > * There's no need to have extra locals, e.g. 'number' in > your code - you can make method calls in string expressions > and it's often more obvious what's going on. > > * I change 'if blanks' for 'unless blanks.empty?'. In Ruby, > everything apart from nil and false evaluate to true. This > includes empty arrays and zero. This works great now! I'll try to remember the #{} syntax. I guess I'm just learning how many ways things can be done in RUBY, and, how wrong some ways can be. I've always been a bit confused by the "<<" syntax. Somehow, I would think it should be ">>" instead, like, you're putting something to something. I guess it is saying that, just from the other way around. The blanks.join statement is brilliant! It's so simple. Thanks again for all your help, Ross. I'll close this issue now and leave you to your real work. Perhaps we'll chat again. Cheers ! -- Posted via http://www.ruby-forum.com/.