用于 Rails 的 CONCAT_WS?

发布于 2024-10-04 05:51:46 字数 439 浏览 2 评论 0原文

无论我使用什么语言,我总是需要显示由某些分隔符分隔的字符串列表。

假设我有一个产品集合,需要显示其名称,并用 ', ' 分隔。 所以我有一个产品集合,其中每个产品都有一个“名称”属性。我正在寻找一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

国际总奸 2024-10-11 05:51:46

你应该尝试使用帮助器 to_sentence。

如果你有一个数组,你可以执行类似

array.to_sentence 的操作。如果你的数组有数据香蕉、苹果、巧克力,它将变成:
香蕉、苹果和巧克力。

所以现在如果你的 AR 模型有一个名为的字段,你可以做类似的事情

MyModel.all.map { |r| r.name }.to_sentence

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
小糖芽 2024-10-11 05:51:46
@products.map(&:title).join(', ')
@products.map(&:title).join(', ')
妞丶爷亲个 2024-10-11 05:51:46

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文