在 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) }
由于重复的 split
和 map
,该实现并不是很快,但您可以自己滚动 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/