From: Ross Bamford Date: 2006-04-13T01:42:36+09:00 Subject: Re: Simple substitutions On Thu, 2006-04-13 at 00:24 +0900, Peter Bailey wrote: > I'm having a bit of > trouble though printing a simple array.length statement. Please check > this out: > > ************************************************ > Dir.chdir('c:/scripts/ruby/temp') > blanks = [] > File.read("test2.ps").scan(/\%\%Page: [\d()]+ > (\d{1,5})\n\%\%PageBoundingBox: \d{1,5} \d{1,5} \d{1,5} > \d{1,5}\n\%\%PageOrientation:/) do > blanks.push($1) > number = blanks.length > blanks.push(" ") > #break > end > > if blanks > File.open("psout2.txt", "w") { |out| out << "Blank Pages in This PDF: > #{blanks}\nNo. of Blanks: #number\n" } > end > ************************************************ > > > 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. -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk