ruby - 在 Ruby 中排序节标题

标签 ruby

在 Ruby 中排序节号字符串的好方法是什么。例如:

sections = ["10", "3", "4", "5", "6", "7", "8", "9", "2", "1", "1.1", "1.1.1", "1.1.2"]
# ["1", "1.1", "1.1.1", "1.1.2", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

最佳答案

如果你必须处理任意嵌套的子部分,那么你可以这样做:

sections = ["10", "3", "4", "5", "6", "7", "8", "9", "2", "1", "1.1", "1.2", "1.2.5"]
sections.sort! { |a,b| a.split('.').map(&:to_i) <=> b.split('.').map(&:to_i) }

由于重复的 splitmap,该实现并不是很快,但您可以自己滚动 Schwartzian Transform如果太慢:

sections.map  { |e| [e, e.split('.').map(&:to_i) ] } \
        .sort { |a, b| a.last <=> b.last } \
        .map  { |e| e.first }

请注意 Enumerable#sort_by为您进行内部施瓦兹变换:

The current implementation of sort_by generates an array of tuples containing the original collection element and the mapped value.

所以你也可以让 sort_by 处理一些丑陋的事情:

section.sort_by { |e| e.split('.').map(&:to_i) }

并获得一目了然的内容。

关于ruby - 在 Ruby 中排序节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701666/

相关文章:

Ruby+Anemone 网络爬虫 : regex to match URLs ending in a series of digits

c# - Ruby 是否像 C# 一样具有 Skip(n)?

ruby-on-rails - 如何正确使用 stub 在rspec中进行测试

ruby-on-rails - 无法将数组存储在 postgresql (rails) 的 json 字段中无法将数组转换为 json

ruby - 在 Rails 4 中使用图像作为单选按钮标签

ruby-on-rails - 将 Ruby on Rails 4 应用程序与 Phonegap 集成以构建原生 iOS 应用程序

ruby - 标点符号模式的正则表达式前瞻/回顾

ruby - 如何测试 Puppet Master 上的文件是否存在

java - 使用 Rjb 从 ruby​​ 调用 java :How to send constant params to java class?

php - 用于 Ruby、PHP 的交互式控制台