使用 Comparable 排序
Coddy 面向 C 开发者的 Ruby 课程的第 37 课,共 48 课。
C 的 qsort 会根据带符号的比较结果修改传入的数组。Ruby 的 sort 可以使用 <=>,Comparable 会基于它生成比较辅助方法,而 sort_by 会计算键。比较结果为零表示排序上相等,而不是对象身份相同。需要确定的顺序时,请明确指定次级排序条件。
C:完整程序
#include <stdio.h>
#include <stdlib.h>
static int compare(const void *left, const void *right) {
int a = *(const int *)left;
int b = *(const int *)right;
return (a > b) - (a < b);
}
int main(void) {
int items[] = {3, 1, 2};
qsort(items, sizeof items / sizeof items[0], sizeof items[0], compare);
printf("%d\n", items[0]);
return 0;
}Ruby:完整程序
words = ["pear", "a", "fig"]
puts words.sort_by { |word| word.length }.join(",")挑战
简单定义 Priority(rank,label),包含只读的 rank 和 label,并引入 Comparable,实现按 rank 排序、再按 label 排序的 <=>。solve 读取 rank:label 标记,对 Priority 对象排序,并返回以逗号分隔的 label;如果没有对象,则返回 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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器