Menu
CoddyTech

Ordering with Comparable

Lesson 37 of 48 in Coddy's Ruby for C Developers course.

C qsort mutates the supplied array according to a signed comparison result. Ruby sort can use <=>, Comparable derives comparison helpers from it, and sort_by computes keys. A comparison result of zero indicates ordering equality rather than object identity. Choose explicit tie-breakers when deterministic order matters.

C: complete program

#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: complete program

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

Challenge

Easy

Define Priority(rank,label), read-only rank and label, include Comparable, and implement <=> ordered by rank then label. solve reads rank:label tokens, sorts Priority objects and returns labels comma-separated, or none.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, priority.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C Developers

Practice on your own: Online Ruby compiler