Forum: Ruby How to check for where a text file begins?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
C5b20b09d5d24bd554f703ff0595696b?d=identicon&s=25 Al Cholic (desertfox)
on 2007-07-03 01:08

Im working with some imported text files and I need check where the
first 2 lines of text occur.  The files can have white space in the
beginning, so I cant just do a split("\n") and take the first two
elements of the array.  Im a bit confused about this stuff.  Here is
what I've been trying to do with regular expressions, but no results

def find_first_two_lines(file)

If anyone has any ideas, please do share!

Thanks in advance!
Fb1a6916e06f221b5b53a6665f9858eb?d=identicon&s=25 Mikel Lindsaar (Guest)
on 2007-07-03 01:20
(Received via mailing list)
def find_first_two_lines(text)

Returns an array of the first two non whitespace lines delimited by \n

(\n is also included in whitespace per strip... handly)


Mikel Lindsaar
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-07-03 16:34
(Received via mailing list)
2007/7/3, Al Cholic <>:
>   /\S\n\S/.match(file)
> end
> If anyone has any ideas, please do share!

What exactly do you want to do with them?  If you have your file
contents in a single string you can do s.sub(/^\s+/, '') in order to
get rid of all leading whitespace.  You can as well do the checking
during reading, probably like this:

contents = nil
io.each do |line|
  contents = "" if contents.nil? && /^\s*$/ =~ line
  contents << line if contents

Kind regards

This topic is locked and can not be replied to.