-
-
Save squaresurf/8600811 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "minitest/autorun" | |
def serial_comma(segments) | |
case segments.count | |
when 1 | |
return segments.first | |
when 2 | |
return segments.join " and " | |
else | |
return segments.push("and #{segments.pop}").join ", " | |
end | |
end | |
class TestSerialComma < MiniTest::Unit::TestCase | |
def possessives | |
%w[hers his yours mine ours] | |
end | |
def test_possessives_1 | |
assert_equal "hers", serial_comma(possessives.slice(0, 1)) | |
end | |
def test_possessives_2 | |
assert_equal "hers and his", serial_comma(possessives.slice(0, 2)) | |
end | |
def test_possessives_3 | |
assert_equal "hers, his, and yours", serial_comma(possessives.slice(0, 3)) | |
end | |
def test_possessives_4 | |
assert_equal "hers, his, yours, and mine", serial_comma(possessives.slice(0, 4)) | |
end | |
def test_possessives_5 | |
assert_equal "hers, his, yours, mine, and ours", serial_comma(possessives) | |
end | |
def places | |
["Seattle", "Lexington", "Athens", "St. Petersberg"] | |
end | |
def test_places_1 | |
assert_equal "Seattle", serial_comma(places.slice(0, 1)) | |
end | |
def test_places_2 | |
assert_equal "Seattle and Lexington", serial_comma(places.slice(0, 2)) | |
end | |
def test_places_3 | |
assert_equal "Seattle, Lexington, and Athens", serial_comma(places.slice(0, 3)) | |
end | |
def test_places_4 | |
assert_equal "Seattle, Lexington, Athens, and St. Petersberg", serial_comma(places) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great points! I've made two more revisions.
The first revision changes
Newcastle
toSt. Petersberg
. This tests the scenario where there are sentence segments that contain spaces.The second revision addresses your comments. My notes are below:
str
variable since it is usually nice to be able to have the method return at the end of the method. In this case it isn't needed and actually hinders readability since it is such a simple method.str_arr
tosegments
as in sentence segments.first
method is. Didn't know it was there since I write in php mostly.<<
shovel since I was making a method call and thought it was more readable, but now I see that interpolation clarifies it a bit more. I'm used to only interpolating variables in php and using concatenation for method calls.