From: David Alan Black Date: 2002-05-06T11:46:32+09:00 Subject: Re: newbie Q: how to strip blank lines from file? Hello -- On Mon, 6 May 2002, Stewart Midwinter wrote: > Well, I've spent a few days reading about Ruby, and want to try my first > project: a little utility that will read a file that has too many blank > lines in it, and strip out all of those blank line (could contain spaces or > tabs). > > As I tackles this, I realise that I need to have a good manual in front of > me, because I'm not getting anywhere. I am definitely confused at this > point, since this problem could be solved in one or two lines, I believe. > Does anyone more experienced have any suggestions? I looked in > rubycookbook.org and couldn't find anything there either. > > Thanks! > > here's my attempt so far, which seems to go into an infinite loop. > > --- > # IO.foreach("snip.txt") { |line| puts line } > arr = IO.readlines("snip.txt") > puts "I read in " + arr.length.to_s + "lines from file." > def blank (s) # looking for blank lines to chop > (s =~ /\S/) != nil > end > i = 0 > while i < arr.length do > if blank(arr[i]) == nil then arr[i] = nil > IO.printf("snip.out") > end > # file.close("snip.out") > end > --- You're working *much* too hard :-) Try this: fout = File.open("snip.out", "w") File.open("snip.txt").each do |line| fout.print line if /\S/.match(line) end David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav