Subscribe to RSS

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.

@users = User.find(:all)
@users.collect {|u| u.firstname}.to_sentence
=> "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.

@users.collect {|u| u.firstname}.to_sentence(:connector => "and of course,", :skip_last_comma => true)
=> "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.

Please share the love of this post by bookmarking it, and sharing it with others. Thanks!

  • Digg
  • del.icio.us
  • description
  • Reddit
  • Technorati
  • BlinkList
  • E-mail this story to a friend!
  • Facebook
  • Live
  • MisterWong
  • Netvouz
  • NewsVine
  • Slashdot
  • SphereIt

3 Comments

  1. carlos
    Posted 24 May, 2008 at 05:55 | Permalink

    How do you handle elements being empty? How do you avoid a comma without text. the first field in my array is required but the other two are not

  2. Posted 24 May, 2008 at 08:07 | Permalink

    @carlos: if they are nil values, you can issue compact, which will remove any nil values.

    ["carlos", nil, "ariejan"].compact 
    => ["carlos", "ariejan"]

    If you are talking about blank (empty string) values, you can issue a select (which will also weed out the nil values)

    ["carlos", nil, "", "ariejan"].select { |name| !name.blank? }
    => ["carlos", "ariejan"]
  3. Posted 3 July, 2008 at 14:10 | Permalink

    Brilliant! I was just writing my own version of this when i thought, “Hang on a minute, maybe Rails can already do this for me!” Sure enough … it can! :)

    Thanks for the little tutorial!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*