instance method
Rational#<=>
(::Integer | ::Rational) -> ::Integer
(untyped) -> ::Integer?
self <=> other → -1, 0, 1, or nil
rational.c
View on GitHub ↗
VALUE
rb_rational_cmp(VALUE self, VALUE other)
{
switch (TYPE(other)) {
case T_FIXNUM:
case T_BIGNUM:
{
get_dat1(self);
if (dat->den == LONG2FIX(1))
return rb_int_cmp(dat->num, other); /* c14n */
other = f_rational_new_bang1(CLASS_OF(self), other);
/* FALLTHROUGH */
}
case T_RATIONAL:
{
VALUE num1, num2;
get_dat2(self, other);
if (FIXNUM_P(adat->num) && FIXNUM_P(adat->den) &&
FIXNUM_P(bdat->num) && FIXNUM_P(bdat->den)) {
num1 = f_imul(FIX2LONG(adat->num), FIX2LONG(bdat->den));
num2 = f_imul(FIX2LONG(bdat->num), FIX2LONG(adat->den));
}
else {
num1 = rb_int_mul(adat->num, bdat->den);
num2 = rb_int_mul(bdat->num, adat->den);
}
return rb_int_cmp(rb_int_minus(num1, num2), ZERO);
}
case T_FLOAT:
return rb_dbl_cmp(nurat_to_double(self), RFLOAT_VALUE(other));
default:
return rb_num_coerce_cmp(self, other, idCmp);
}
}
Compares self and other.
Returns:
-
-1, ifselfis less thanother. -
0, if the two values are the same. -
1, ifselfis greater thanother. -
nil, if the two values are incomparable.
Examples:
Example
Rational(2, 3) <=> Rational(4, 3) # => -1 Rational(2, 1) <=> Rational(2, 1) # => 0 Rational(2, 1) <=> 2 # => 0 Rational(2, 1) <=> 2.0 # => 0 Rational(2, 1) <=> Complex(2, 0) # => 0 Rational(4, 3) <=> Rational(2, 3) # => 1 Rational(4, 3) <=> :foo # => nil
Class Rational includes module Comparable, each of whose methods uses Rational#<=> for comparison.