开发者

CONCAT_WS for Rails?

开发者 https://www.devze.com 2023-01-26 20:35 出处:网络
No matter what language I\'m using I always need to display a list of strings separated by some delimiter.

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 no开发者_JAVA百科t be there.

Ex:

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

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

Thanks!


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消