DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Write Out An Array As A List With Commas And An 'and'

08.23.2005
| 8345 views |
  • submit to reddit
        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

Chris O'Sullivan replied on Sat, 2007/04/21 - 12:14pm

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