Add Formatter::enumeration.

This commit is contained in:
Markus Reiter 2018-06-20 20:32:28 +02:00
parent 2aa7597e70
commit 7671606ddc
2 changed files with 25 additions and 0 deletions

View File

@ -76,4 +76,22 @@ describe Formatter do
expect(described_class.pluralize(2, "new formula")).to eq("2 new formulae")
end
end
describe "::enumeration" do
it "returns nil if given no arguments" do
expect(described_class.enumeration).to be nil
end
it "returns the input as string if there is only one argument" do
expect(described_class.enumeration(1)).to eq("1")
end
it "concatenates two items with “and”" do
expect(described_class.enumeration(1, 2)).to eq("1 and 2")
end
it "concatenates all items with a comma and appends the last with “and”" do
expect(described_class.enumeration(1, 2, 3)).to eq("1, 2 and 3")
end
end
end

View File

@ -108,4 +108,11 @@ module Formatter
show_count ? "#{count} #{words}" : words
end
def enumeration(*items)
*items, last = items.map(&:to_s)
return last if items.empty?
"#{items.join(", ")} and #{last}"
end
end