Menu
CoddyTech

使用 Comparable 排序

Coddy 面向 GDScript 开发者的 Ruby 课程的第 37 课,共 48 课。

GDScript 的 Array.sort_custom 使用返回布尔值的先后顺序判断函数,并会修改数组。Ruby 的比较排序使用 <=> 的结果,而 Comparable 会基于该操作派生出关系运算辅助方法;sort_by 会计算键。需要布尔值时返回带符号的比较结果会改变含义。排序比较结果为零并不代表对象相同,明确的次级排序条件有助于让输出保持确定。

GDScript:完整程序

extends SceneTree
func _init():
    var scores = [3, 9, 3]
    scores.sort_custom(func(a, b): return a > b)
    var text = PackedStringArray()
    for score in scores:
        text.append(str(score))
    print(",".join(text))
    quit()

Ruby:完整程序

words = ["pear", "a", "fig"]
puts words.sort_by { |word| word.length }.join(",")
challenge icon

挑战

简单

定义 Priority(rank,label),提供只读的 rank 和 label,包含 Comparable,并实现按 rank、再按 label 排序的 <=>。solve 读取 rank:label 标记,对 Priority 对象排序,并以逗号分隔的形式返回标签;如果没有对象,则返回 none。

让 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查所需的公共 API。

你的代码应写在 exercise.rb 和 priority.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。

亲手试试

require_relative 'exercise'
require_relative 'priority'
def check(value)
  raise 'Public API check failed' unless value
end
a = Priority.new(2, "a"); b = Priority.new(2, "b")
check(a.rank == 2 && a.label == "a" && a < b && a == Priority.new(2, "a"))
check(Priority.ancestors.include?(Comparable))

puts solve(STDIN.read)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 GDScript 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器