用于 Rails 的 CONCAT_WS?
无论我使用什么语言,我总是需要显示由某些分隔符分隔的字符串列表。
假设我有一个产品集合,需要显示其名称,并用 ', '
分隔。 所以我有一个产品集合,其中每个产品都有一个“名称”属性。我正在寻找一些 Rails 方法/帮助程序(如果它不存在,也许你可以给我一些想法以 Rails 方式构建它),它将接收一个集合,一个将在每个集合项上调用的属性/方法和分隔符的字符串。
但我想要的东西末尾不包含分隔符,因为我将以“笔记本、计算机、键盘、鼠标”结尾,最后两个字符不应该在那里。
例如:
concat_ws(@products, :title, ", ")
#displays: Notebook, Computer, Keyboard, Mouse
假设@products 有 4 个具有该名称的产品。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你应该尝试使用帮助器 to_sentence。
如果你有一个数组,你可以执行类似
array.to_sentence 的操作。如果你的数组有数据香蕉、苹果、巧克力,它将变成:
香蕉、苹果和巧克力。
所以现在如果你的 AR 模型有一个名为的字段,你可以做类似的事情
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
正如@VP 提到的,Array#to_sentence 在 Rails 中很好地完成了这项工作。它的代码在这里:
https: //github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/conversions.rb
也就是说,它对牛津逗号的使用是有问题的:-)
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 :-)