有没有一种方法可以对“维生素 B12”进行排序?前面不是“维生素B6”吗?

发布于 2024-11-02 08:03:33 字数 168 浏览 4 评论 0原文

在 Ruby on Rails 中,默认排序顺序

Vitamin A
Vitamin B12
Vitamin B6

为 是否有一种机制或快速方法可以按自然语言方式排序,以便 B6 显示在 B12 之前?

In Ruby on Rails, the default sort order will be

Vitamin A
Vitamin B12
Vitamin B6

Is there a mechanism or quick way so that it will sort by a natural language way so that B6 shows before B12?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

悟红尘 2024-11-09 08:03:33

尝试类似的操作:

class Array
  def smart_sort
    sort_by{|s| (' '+s).scan(/(\d+)|(\D+)/).map{|d, s| s || d.to_i}}
  end
end

a = ['Vitamin A', 'Vitamin B12', 'Vitamin B6']
p a.smart_sort

# => ["Vitamin A", "Vitamin B6", "Vitamin B12"]

它按数字和非数字交替排序。

b = ['3c17d', '1a34be',  '3x1a', '1b01c', '1a34bb']
p b.smart_sort

# => ["1a34bb", "1a34be", "1b01c", "3c17d", "3x1a"]

这可能类似于 Windows 中对目录中的文件名进行排序时所做的操作。


Update: A newer version. Doesn't need ' '+, as it is automatically supplied by split. It also removes the redundancy of specifying the complementary \d and \D in the regex.

class Array
  def smart_sort
    sort_by{|s| s.split(/(\d+)/).each_slice(2).flat_map{|s, d| [s, d.to_i]}}
  end
end

Try something like:

class Array
  def smart_sort
    sort_by{|s| (' '+s).scan(/(\d+)|(\D+)/).map{|d, s| s || d.to_i}}
  end
end

a = ['Vitamin A', 'Vitamin B12', 'Vitamin B6']
p a.smart_sort

# => ["Vitamin A", "Vitamin B6", "Vitamin B12"]

It sorts alternatively by digits and by non-digits.

b = ['3c17d', '1a34be',  '3x1a', '1b01c', '1a34bb']
p b.smart_sort

# => ["1a34bb", "1a34be", "1b01c", "3c17d", "3x1a"]

This is probably similar to what is done in Windows when sorting the file names within a directory.


Update: A newer version. Doesn't need ' '+, as it is automatically supplied by split. It also removes the redundancy of specifying the complementary \d and \D in the regex.

class Array
  def smart_sort
    sort_by{|s| s.split(/(\d+)/).each_slice(2).flat_map{|s, d| [s, d.to_i]}}
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文