Ruby Tidbits: Sentencizing A List of Things

Say you have an array. Maybe it is ["Larry", "Moe", "Curly"]. You’d like to display this as a sentence, not just a join, so it would read "Larry, Moe and Curly". That would be nice. Of course, you can’t guarantee that your array will have three items. Maybe tomorrow it will be just ["Frodo"], or ["Groucho", "Chico", "Harpo", "Zeppo"].

No problem. Let’s say your array is list. You could write:

1
2
list.size > 1 ? "#{list[0..(list.size - 2)].join(', ')} \
  and #{list.last}" : "#{list.first}"