[Note: parts of this message were removed to make it a legal post.]
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.)
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