如何对“章号"进行排序?像1.1.1、1.2.1、1.2.46等? [英] How to sort "chapter numbers" like 1.1.1, 1.2.1, 1.2.46, etc.?
本文介绍了如何对“章号"进行排序?像1.1.1、1.2.1、1.2.46等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种快速的方法来对Ruby中的章号"进行排序?
Is there a quick way to sort "chapter numbers" in Ruby?
1.1.1
1.1.2
1.2.1
1.3.1
1.3.2
1.3.3
10.42.64
etc.?
我必须写一个枚举器或类似的东西吗?
Do I have to write an enumerator or something like that?
推荐答案
在Ruby中,Array
s按字典顺序排序,因此最简单的方法是将它们转换为Array
s然后对其进行排序:
In Ruby, Array
s are ordered lexicographically, so the easiest way would be to convert these into Array
s and then sort them:
chapters = %w[1.1.1 1.1.2 1.2.1 1.3.1 1.3.2 1.3.3 10.42.64]
chapters.sort_by {|chapter| chapter.split('.').map(&:to_i) }
# => ["1.1.1", "1.1.2", "1.2.1", "1.3.1", "1.3.2", "1.3.3", "10.42.64"]
当然, real 解决方案是使用对象,而不是对数字字符串数组进行拖拉.毕竟,Ruby是一种面向对象的语言,而不是一种面向字符串数组的语言:
Of course, the real solution would be to use objects instead of slugging around arrays of strings of numbers. After all, Ruby is an object-oriented language, not an arrays-of-strings-of-numbers-oriented language:
class ChapterNumber
include Comparable
def initialize(*nums)
self.nums = nums
end
def <=>(other)
nums <=> other.nums
end
def to_s
nums.join('.')
end
alias_method :inspect, :to_s
protected
attr_reader :nums
private
attr_writer :nums
end
chapters = [ChapterNumber.new(1, 1, 1), ChapterNumber.new(1, 1, 2),
ChapterNumber.new(1, 2, 1), ChapterNumber.new(1, 3, 1),
ChapterNumber.new(1, 3, 2), ChapterNumber.new(1, 3, 3),
ChapterNumber.new(10, 42, 64)]
chapters.sort
# => [1.1.1, 1.1.2, 1.2.1, 1.3.1, 1.3.2, 1.3.3, 10.42.64]
这篇关于如何对“章号"进行排序?像1.1.1、1.2.1、1.2.46等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文