Menu
CoddyTech

Comparable을 사용한 정렬

Coddy의 C 개발자를 위한 Ruby 코스 레슨. 48개 중 37번째.

C의 qsort는 부호 있는 비교 결과에 따라 전달된 배열을 변경합니다. Ruby의 sort는 <=>를 사용할 수 있고, Comparable은 이를 바탕으로 비교 도우미 메서드를 제공하며, sort_by는 키를 계산합니다. 비교 결과가 0이면 객체의 동일성이 아니라 정렬상 동등함을 나타냅니다. 결정론적 순서가 중요하다면 명시적인 타이브레이커를 선택하세요.

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(",")
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실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 Ruby의 모든 레슨

직접 연습해 보세요: 온라인 Ruby 컴파일러