From: Chris Date: 2002-05-06T11:53:33+09:00 Subject: Re: newbie Q: how to strip blank lines from file? In article , 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 > --- The reason for your infinite loop is that in your while loop, you never increment i. IO.readlines("snip.txt").collect { |x| x.strip unless x.strip == "" } Iterators are your friend. :-)