From: John Sikora Date: 2010-10-04T12:56:34+09:00 Subject: Re: save only first line from string? Terry Michaels wrote: > Hi. What's the most simple and elegant way to remove all the contents of > a String except for the first line? (Assume string consist of one line, > multiple lines, or no lines, and assume that we don't know which OS we > are on.) I don't know about the most elegant or simple way, but how about this: string.sub!(/^(.*\n?)((?im).+)?/, '\1').chomp Some tests: string_1 = < "hello there." p string_2.sub!(regex, '\1').chomp # => "hi there" p string_3.sub!(regex, '\1').chomp # => "" p string_4.sub!(regex, '\1').chomp # => "hi" p string_5.sub!(regex, '\1').chomp # => "" I don't think that the ^ is really needed, but I included it anyway. Also, don't be surprised if someone finds a fault with this or comes up with a better solution (I never figured I would be giving advice on regexs). -- Posted via http://www.ruby-forum.com/.