Comparable 모듈

Comparable 모듈

Comparable 믹스인은 객체가 서로 순서를 가질(비교 가능한) 클래스에서 사용해요. 이 믹스인을 쓰는 클래스는 반드시 <=> 연산자를 정의해야 해요. <=>는 리시버를 다른 객체와 비교해서, 리시버가 상대보다 작으면 0보다 작은 값, 같으면 0, 크면 0보다 큰 값을 반환해요. 비교할 수 없는 상대라면 <=>nil을 반환해야 해요. Comparable<=>를 이용해 일반적인 비교 연산자(<, <=, ==, >=, >)와 between? 메서드를 구현해요.

class StringSorter
  include Comparable

  attr :str
  def <=>(other)
    str.size <=> other.str.size
  end

  def initialize(str)
    @str = str
  end

  def inspect
    @str
  end
end

s1 = StringSorter.new("Z")
s2 = StringSorter.new("YY")
s3 = StringSorter.new("XXX")
s4 = StringSorter.new("WWWW")
s5 = StringSorter.new("VVVVV")

s1 < s2                       #=> true
s4.between?(s1, s3)           #=> false
s4.between?(s3, s5)           #=> true
[ s3, s2, s5, s4, s1 ].sort   #=> [Z, YY, XXX, WWWW, VVVVV]

출처: Ruby 3.3 API

본문

Comparable 모듈이 제공하는 메서드는 모두 <=>를 사용해요.

  • <: self가 주어진 객체보다 작은지 반환해요.
  • <=: self가 주어진 객체보다 작거나 같은지 반환해요.
  • ==: self가 주어진 객체와 같은지 반환해요.
  • >: self가 주어진 객체보다 큰지 반환해요.
  • >=: self가 주어진 객체보다 크거나 같은지 반환해요.
  • between?: self가 두 객체 사이에 있으면 true를 반환해요.

obj < other → true or false

리시버의 <=> 메서드에 기반해 두 객체를 비교해, 반환값이 0보다 작으면 true를 반환해요.

static VALUE
cmp_lt(VALUE x, VALUE y)
{
    return RBOOL(cmpint(x, y) < 0);
}

obj <= other → true or false

두 객체를 리시버의 <=>로 비교해, 반환값이 0보다 작거나 같으면 true를 반환해요.

static VALUE
cmp_le(VALUE x, VALUE y)
{
    return RBOOL(cmpint(x, y) <= 0);
}

obj == other → true or false

두 객체를 리시버의 <=>로 비교해, 반환값이 0이면 true를 반환해요. objother가 같은 객체인 경우에도 true를 반환해요.

static VALUE
cmp_equal(VALUE x, VALUE y)
{
    VALUE c;
    if (x == y) return Qtrue;

    c = rb_exec_recursive_paired_outer(cmp_eq_recursive, x, y, y);

    if (NIL_P(c)) return Qfalse;
    return RBOOL(rb_cmpint(c, x, y) == 0);
}

obj > other → true or false

두 객체를 리시버의 <=>로 비교해, 반환값이 0보다 크면 true를 반환해요.

static VALUE
cmp_gt(VALUE x, VALUE y)
{
    return RBOOL(cmpint(x, y) > 0);
}

obj >= other → true or false

두 객체를 리시버의 <=>로 비교해, 반환값이 0보다 크거나 같으면 true를 반환해요.

static VALUE
cmp_ge(VALUE x, VALUE y)
{
    return RBOOL(cmpint(x, y) >= 0);
}

between?(min, max) → true or false

obj <=> min이 0보다 작거나 obj <=> max가 0보다 크면 false, 그 외에는 true를 반환해요.

3.between?(1, 5)               #=> true
6.between?(1, 5)               #=> false
'cat'.between?('ant', 'dog')   #=> true
'gnu'.between?('ant', 'dog')   #=> false
static VALUE
cmp_between(VALUE x, VALUE min, VALUE max)
{
    return RBOOL((cmpint(x, min) >= 0 && cmpint(x, max) <= 0));
}

clamp(min, max) → obj

clamp(range) → obj

(min, max) 형태에서는, obj <=> min이 0보다 작으면 min을, obj <=> max가 0보다 크면 max를, 그 외에는 obj를 반환해요.

12.clamp(0, 100)         #=> 12
523.clamp(0, 100)        #=> 100
-3.123.clamp(0, 100)     #=> 0

'd'.clamp('a', 'f')      #=> 'd'
'z'.clamp('a', 'f')      #=> 'f'

minnil이면 obj보다 작은 것으로, maxnil이면 obj보다 큰 것으로 간주해요.

-20.clamp(0, nil)           #=> 0
523.clamp(nil, 100)         #=> 100

(range) 형태에서는, obj <=> range.begin이 0보다 작으면 range.begin을, obj <=> range.end가 0보다 크면 range.end를, 그 외에는 obj를 반환해요.

12.clamp(0..100)         #=> 12
523.clamp(0..100)        #=> 100
-3.123.clamp(0..100)     #=> 0

'd'.clamp('a'..'f')      #=> 'd'
'z'.clamp('a'..'f')      #=> 'f'

range.beginnil이면 obj보다 작은 것으로, range.endnil이면 obj보다 큰 것으로 간주해요.

-20.clamp(0..)           #=> 0
523.clamp(..100)         #=> 100

range.end가 제외형(exclusive)이면서 nil이 아니면 예외가 발생해요.

100.clamp(0...100)       # ArgumentError
static VALUE
cmp_clamp(int argc, VALUE *argv, VALUE x)
{
    VALUE min, max;
    int c, excl = 0;

    if (rb_scan_args(argc, argv, "11", &min, &max) == 1) {
        VALUE range = min;
        if (!rb_range_values(range, &min, &max, &excl)) {
            rb_raise(rb_eTypeError, "wrong argument type %s (expected Range)",
                     rb_builtin_class_name(range));
        }
        if (!NIL_P(max)) {
            if (excl) rb_raise(rb_eArgError, "cannot clamp with an exclusive range");
        }
    }
    if (!NIL_P(min) && !NIL_P(max) && cmpint(min, max) > 0) {
        rb_raise(rb_eArgError, "min argument must be less than or equal to max argument");
    }

    if (!NIL_P(min)) {
        c = cmpint(x, min);
        if (c == 0) return x;
        if (c < 0) return min;
    }
    if (!NIL_P(max)) {
        c = cmpint(x, max);
        if (c > 0) return max;
    }
    return x;
}