Method: Float#<=>

Defined in:
numeric.c

#<=>(other) ⇒ -1, ...

Returns a value that depends on the numeric relation between self and other:

  • -1, if self is less than other.

  • 0, if self is equal to other.

  • 1, if self is greater than other.

  • nil, if the two values are incommensurate.

Examples:

2.0 <=> 2              # => 0
2.0 <=> 2.0            # => 0
2.0 <=> Rational(2, 1) # => 0
2.0 <=> Complex(2, 0)  # => 0
2.0 <=> 1.9            # => 1
2.0 <=> 2.1            # => -1
2.0 <=> 'foo'          # => nil

This is the basis for the tests in the Comparable module.

Float::NAN <=> Float::NAN returns an implementation-dependent value.

Returns:

  • (-1, 0, +1, nil)


1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
# File 'numeric.c', line 1670

static VALUE
flo_cmp(VALUE x, VALUE y)
{
    double a, b;
    VALUE i;

    a = RFLOAT_VALUE(x);
    if (isnan(a)) return Qnil;
    if (RB_INTEGER_TYPE_P(y)) {
        VALUE rel = rb_integer_float_cmp(y, x);
        if (FIXNUM_P(rel))
            return LONG2FIX(-FIX2LONG(rel));
        return rel;
    }
    else if (RB_FLOAT_TYPE_P(y)) {
        b = RFLOAT_VALUE(y);
    }
    else {
        if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
            if (RTEST(i)) {
                int j = rb_cmpint(i, x, y);
                j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
                return INT2FIX(j);
            }
            if (a > 0.0) return INT2FIX(1);
            return INT2FIX(-1);
        }
        return rb_num_coerce_cmp(x, y, id_cmp);
    }
    return rb_dbl_cmp(a, b);
}