Rails Tip Snippet: Create a comma-seperate list
Do you have the need to create a list of roles a certain user belongs to? Enumerate the users attached to a company? All you want is a simple list with the names seperated by commas.
Users: John, Dick, Harry
With Ruby on Rails this is really easy. You probably have a collection of user objects. All you want is a list of names:
@users.collect{|u| u.name}.join(', ')
Read more Tip Snippets?
Yeah, Rails provides an extension to the Array class allowing something like this:
@users.collect(&:name).to_sentence
=> “Tom, Dick, and Harry”
http://api.rubyonrails.com/classes/ActiveSupport/CoreExtensions/Array/Conversions.html#M000372
@Brendan: It would be “Tom, Dick and Harry”, but that’s not the point.
This just one of those great little hidden methods that make Rails so very nice to work with.
Thanks for pointing it out!
by Ariejan.net » Blog Archive » Rails Snippet: Write like Orwell with to_sentence
[...] Snippet: Write like Orwell with to_sentence RubyOnRails May 9th, 2007 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 [...]















Or even shorter
@users.collect(&:name).join(’, ‘)
I seem to remember there was some spice in Rails that could do a join so that it looked like a sentence, with a dot at the end and stuff.