From: Joseph Paish Date: 2006-04-24T00:38:47+09:00 Subject: Re: how to ensure no blank lines in DATA statements On Mon, 24 Apr 2006 00:20:46 +0900 dblack@wobblini.net wrote: > Hi -- > > On Mon, 24 Apr 2006, Joseph Paish wrote: > > > suppose i have the following piece of code to read some data (input by > > the user) following __END__ > > > > while line = DATA.gets > > one_record = line.chomp!.split > > # do stuff > > end > > > > > > > > __END__ > > > > bought 2 widgets 17.99 > > sold 12 widgets 22.49 > > > > bought 11 things 12.99 > > > > sold 5 things 10.49 > > > > > > as you can see, there is a blank line ahead of the first line of data (i > > don't want that), and there may be one or more blank lines or lines > > containing spaces after the data or even between the lines of data. > > > > i can't control what the user will do here, but i need to take it into > > account. any suggestions on how to ensure that any line i read contains > > the 4 desired fields and doesn't contain anything else (even 4 blank > > spaces like between the last bought and sold records)? > > Here's a nice way to avoid worrying about the spaces, though it may > run aground if you have lines that have non-spaces and are malformed: > > require 'scanf' > > DATA.scanf("%s%d%s%f") do |action, num, item, price| > puts "#{action} #{num} #{item} at $#{price}, total $#{price * num}" > end > > Output (with your sample): > > bought 2 widgets at $17.99, total $35.98 > sold 12 widgets at $22.49, total $269.88 > bought 11 things at $12.99, total $142.89 > sold 5 things at $10.49, total $52.45 > > > David > this is exactly what i needed. thank you joe