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}"

2 Responses to “Ruby Tidbits: Sentencizing A List of Things”


  1. 1 Luke Francl

    Or, if you're using ActiveSupport, you could use Array#to_sentence.

    ['Larry', 'Moe', 'Curly'].to_sentence => “Larry, Moe, and Curly”

    http://api.rubyonrails.org/classes/ActiveSuppor...

  2. 2 philcrissman

    D'oh! I _nearly_ asked the other day if Rails had a builtin method for this, decided not to, searched google and didn't see this.

    My option is a lot shorter than to_sentence's code, but on the other hand, to_sentence *does* allow you to decide whether or not to skip the last comma, and to choose a connector other than “and” if you want. So much for DRY.

Comments are currently closed.



Fork me on GitHub