Last updated

Rails Snippet: Write like Orwell with to_sentence

A few weeks ago I posted an article that explained how to create a comma separated list from a hash of objects. When I was browsing the Rails API documentation I came across a method named to_sentence.

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.

1@users = User.find(:all)
2@users.collect {|u| u.firstname}.to_sentence
3=> "Tom, Dick, and Harry"

Of you course, you can specify the last separator, called the connector. Also it’s possible to not show the last comma.

1@users.collect {|u| u.firstname}.to_sentence(:connector => "and of course,", :skip_last_comma => true)
2=> "tom, Dick and of course, Harry"

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.