devroom.io/drafts/2007-05-09-rails-snippet-write-like-orwell-with-to_sentence.md

21 lines
1.4 KiB
Markdown
Raw Normal View History

2013-03-22 22:53:57 +00:00
---
title: "Rails Snippet: Write like Orwell with to_sentence"
kind: article
slug: rails-snippet-write-like-orwell-with-to_sentence
created_at: 2007-05-09
tags:
- General
- RubyOnRails
- Features
---
A few weeks ago I posted <a href="http://ariejan.net/2007/03/27/rails-tip-snippet-create-a-comma-seperate-list/">an article</a> that explained how to create a comma separated list from a hash of objects. When I was browsing the <a href="http://api.rubyonrails.com">Rails API documentation</a> I came across a method named <a href="http://api.rubyonrails.com/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000372">to_sentence</a>.
What this little bugger does is create a human readable, comma separated list of items in an array or hash. But the big difference here is that you can specify what the last separator must be. By default this is set to 'and'. See the following example.
<pre lang="ruby">@users = User.find(:all)
@users.collect {|u| u.firstname}.to_sentence
=> "Tom, Dick, and Harry"</pre>
Of you course, you can specify the last separator, called the connector. Also it's possible to not show the last comma.
<pre lang="ruby">@users.collect {|u| u.firstname}.to_sentence(:connector => "and of course,", :skip_last_comma => true)
=> "tom, Dick and of course, Harry"</pre>
I bet this will greatly simplify the way you list names, tags, categories or whatever else you want summed up in a comma separated list with a human touch.