Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Write out an array as a list with commas and an 'and' (See related posts)

Actually, you can customize the separators to your needs.

def text_list(listtext,sep1=", ", sep2=", and ")
  n=listtext.size
  if n>1 : (listtext.first(n-1)).join(sep1) + sep2 +listtext.last 
  else listtext.first end
end

text_list(["cat", "dog", "bird"]) => "cat, dog, and bird"

Comments on this post

thechrisoshow posts on Feb 09, 2008 at 18:54
If you're using Rails you can also use the sweet built-in array extension to_sentence method like this:
['cat', 'dog', 'bird'].to_sentence #Returns cat, dog, and bird

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts