Skip to content

Instantly share code, notes, and snippets.

@caius
Created July 3, 2016 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caius/a04642ec3f6b0cb012c3e66aea3264a7 to your computer and use it in GitHub Desktop.
Save caius/a04642ec3f6b0cb012c3e66aea3264a7 to your computer and use it in GitHub Desktop.
# Turn a list of elements into a sentence listing them
#
# Expected outcomes:
# [] => ""
# %w(one) => "one"
# %(one two) => "one and two"
# %w(one two three) => "one, two and three"
#
def list_sentence(elements)
case elements.size
when 0
""
when 1
elements.first
else
[elements[0..-2].join(", "), "and", elements.last].join(" ")
end
end
list_sentence [] # => ""
list_sentence %w(one) # => "one"
list_sentence %w(one two) # => "one and two"
list_sentence %w(one two three) # => "one, two and three"
list_sentence %w(one two three four five six seven) # => "one, two, three, four, five, six and seven"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment