views:

55

answers:

1
+1  Q: 

English list...

I have a scenario where I need to supply users a message. The message can be in the following forms:

  • "John likes to eat < b>squirrel< /b>."
  • "John likes to eat < b>squirrel< /b> and < b>gator< /b>."
  • "John likes to eat < b>squirrel< /b>, < b>gator< /b> and < b>birdpoop< /b>."
  • "John likes to eat < b>squirrel< /b>, < b>gator< /b>, < b>birdpoop< /b> and < b>marshmallows< /b>."
  • ...

So I think you can see the English pattern here. My question is how do I take an array of things (1...n) that John likes to eat (e.g., squirrel) and turn it dynamically into one of the above English list forms depending upon the number of elements in the array?

+3  A: 

Since the question has the ruby-on-rails tag, I'll assume you're working in a Rails environment, in which case Array#to_sentence (added by ActiveSupport) is what you're looking for.

Greg Campbell
this looks good, but i need to format each food with bold. can i accomplish that using this method?
keruilin
`array.map{|a| "<b>#{a}</b>"}.to_sentence`
Geoff Lanotte
An addition to this, in Rails 2.3 to_sentence follows the Chicago manual of style with regards to the last comma so you get 1, 2, and 3 instead of the British English 1, 2 and 3. You may need to change how to_sentence works (last_word_connector) http://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L36 - fairly trivial i18n change.
Omar Qureshi