From: Josh Cheek Date: 2010-10-04T14:07:25+09:00 Subject: Re: save only first line from string? --001485f3e6084ba8e20491c3766a Content-Type: text/plain; charset=ISO-8859-1 On Sun, Oct 3, 2010 at 9: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.) > -- > Posted via http://www.ruby-forum.com/. > > require 'test/unit' def first_line(string) string.gsub( /$[^\Z]*\Z/m , '' ) end class FirstLineTest < Test::Unit::TestCase def test_return_empty_string_when_given_empty_string assert_equal "" , first_line("") end def test_returns_string_when_given_one_line_string_with_no_newline string = "abc def ghi" assert_equal string , first_line(string.dup) end def test_returns_string_without_newline_when_given_one_line_string_with_newline string = "abc def ghi\n" assert_equal string.chomp , first_line(string.dup) end def test_returns_first_line_without_newline_when_given_multi_line_string string = "abc def ghi\njkl mno pqr\nstu vwx yz" assert_equal "abc def ghi" , first_line(string.dup) end def test_does_not_mutate_original_string string = "abc def ghi\njkl mno pqr\nstu vwx yz" first_line string assert_equal "abc def ghi\njkl mno pqr\nstu vwx yz" , string end end --001485f3e6084ba8e20491c3766a--