Question

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!

Was it helpful?

Solution

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

OTHER TIPS

@products.map(&:title).join(', ')

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 :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top