0

No matter what language I'm using I always need to display a list of strings separated by some delimiter.

Let's say, I have a collection of products and need to display its names separated by ', '. So I have a collection of Products, where each one has a 'name' attribute. I'm looking for some Rails method/helper (if it doesn't exist, maybe you can give me ideas to build it in a rails way) that will receive a collection, an attribute/method that will be called on each collection item and a string for the separator.

But I want something that does not include the separator at the end, because I will end with "Notebook, Computer, Keyboard, Mouse, " that 2 last characters should not be there.

Ex:

concat_ws(@products, :title, ", ")
#displays: Notebook, Computer, Keyboard, Mouse

Supposing @products has 4 products with that names of course.

Thanks!

empz
  • 11,509
  • 16
  • 65
  • 106

3 Answers3

1

you should try the helper to_sentence.

If you have an array, you can do something like

array.to_sentence. If your array has the data banana, apple, chocolate it will become: banana, apple and chocolate.

So now if you have your AR Model with a field named, you could do something like

MyModel.all.map { |r| r.name }.to_sentence
VP.
  • 5,122
  • 6
  • 46
  • 71
1
@products.map(&:title).join(', ')
glebm
  • 20,282
  • 8
  • 51
  • 67
1

As @VP mentioned, Array#to_sentence does this job well in rails. The code for it is here:

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/conversions.rb

Saying that, its use of the Oxford Comma is questionable :-)

noodl
  • 17,143
  • 3
  • 57
  • 55
  • Yeah, I don't like that Oxford Comma... Luckily is easily editable using locales (support.array.last_word_connector), which anyway I need because it's a multi-language site =) – empz Nov 24 '10 at 18:15