From: Justin Collins Date: 2010-10-04T12:51:36+09:00 Subject: Re: save only first line from string? On 10/03/2010 07:19 PM, 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.) > Assuming you mean to actually modify the string, you could do this: irb(main):001:0> "a string\nwith multiple\nlines".gsub! /\A(.*?)$(.*)\z/m, '\1' => "a string" irb(main):002:0> "a string with one line".gsub! /\A(.*?)$(.*)\z/m, '\1' => "a string with one line" irb(main):003:0> "".gsub! /\A(.*?)$(.*)\z/m, '\1' => "" If you don't need to modify the string: irb(main):004:0> "a string\nwith multiple\nlines".match(/\A.*?$/)[0] => "a string" irb(main):005:0> "a string with one line".match(/\A.*?$/)[0] => "a string with one line" irb(main):006:0> "".match(/\A.*?$/)[0] => "" -Justin