#to_sentence With Links

Here's a snippet useful for displaying categories on a post, or a similar array of links.

@post.categories.collect { |c| link_to(c.name, category_path(c)) }.to_sentence
#=> <a href="/categories/tutorials">Tutorials</a>, <a href="/categories/web">Web</a> and <a href="/categories/design">Design</a>

Here's the API doc of #to_sentence for reference:

Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:

  - :words_connector - The sign or word used to join the elements in arrays with two or more elements (default: “, “)
  - :two_words_connector - The sign or word used to join the elements in arrays with two elements (default: “ and “)
  - :last_word_connector - The sign or word used to join the last element in arrays with three or more elements (default: “, and “)

Enjoy the summer, and don't work to hard!

Filed in Tutorials.