gpt4 book ai didi

ruby - 如何像 1.1.1、1.2.1、1.2.46 等那样对 "chapter numbers"进行排序?

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:18 27 4
gpt4 key购买 nike

在 Ruby 中有快速排序“章节编号”的方法吗?

1.1.1
1.1.2
1.2.1
1.3.1
1.3.2
1.3.3
10.42.64
etc.?

我是否必须编写一个枚举器或类似的东西?

最佳答案

在 Ruby 中,Array 是按字典顺序排列的,因此最简单的方法是将它们转换为 Array,然后对它们进行排序:

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"]

当然,真正的解决方案是使用对象而不是绕过数字字符串数组。毕竟,Ruby 是一种面向对象的语言,而不是一种面向数字字符串数组的语言:

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]

关于ruby - 如何像 1.1.1、1.2.1、1.2.46 等那样对 "chapter numbers"进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388104/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com