6

Rails Snippet: Write like Orwell with to_sentence

 3 years ago
source link: https://www.devroom.io/2007/05/09/rails-snippet-write-like-orwell-with-to_sentence/?utm_campaign=Feed%3A+ariejan+%28ariejan%7Cdevroom.io%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rails Snippet: Write like Orwell with to_sentence

Posted: 2007-05-09 - Last updated: 2019-06-05

Tagged general rubyonrails features

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.

My site is free of ads and trackers. I record privacy-respecting usage statistics with Fathom.

Was this post helpful to you? Why not ☕ Buy me a coffee

Copyright © 1999-2020 Ariejan de Vroom <[email protected]>

Live now; make now always the most precious time. Now will never come again.
    – Jean-Luc Picard


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK