27 Mar 2007, 11:26am

by Ariejan de Vroom

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?

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
17 Apr 2007, 9:02am
by Stian Haklev


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.

7 May 2007, 8:05pm
by Brendan


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

7 May 2007, 9:05pm
by Ariejan


@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!

[...] 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 [...]

*name

*e-mail

web site

leave a comment