From: Justin Collins Date: 2008-02-28T06:46:08+09:00 Subject: Re: checking for blank line Jeff Miller wrote: > Hello, > I know this is an elementary problem, but I have been fooling around > with RoR for a little while and am now in need of doing some ruby > scripting. I am reading a text file line by line and I want to check if > the line is empty. For example: > > file = File.new("test.txt", "r") > while (line = file.gets) > @array = line.split(':') > if @array[0] == 'cn' > puts "#{@array[1]}" > end > if @array[0] == 'title' > puts " Title: #{@array[1]}" > end > if @array[0] == 'company' > puts " Company: #{@array[1]}" > end > if @array[0] == nil #~ THIS IS THE LINE I'M TALKING > ABOUT > puts "-----" > end > end > file.close > > The input file just looks like this: > > cn: John Smith > title: executive > company: ReallyCoolSoftware, inc. > > cn: John Doe > title: janitor > company: NotSoCoolSoftware, inc. > > etc... > > How can I pick up those blank lines in my IF statement? I tried nil and > '', but neither seem to work. > > Any help is appreciated! > Thank you!! > - Jeff > Remember, "blank" lines might not be truly empty: irb(main):001:0> a = gets => "\n" irb(main):002:0> a.split(":") => ["\n"] Also, using split on an empty string is not going to give you nil, but an empty array: irb(main):003:0> "".split(":") => [] If you don't want the line endings in your strings, try using while (line = file.gets.chomp) or while (line = file.gets.strip) instead. -Justin