instance method
Complex#to_r
() -> ::Rational
to_r → rational
complex.c
View on GitHub ↗
static VALUE
nucomp_to_r(VALUE self)
{
get_dat1(self);
if (RB_FLOAT_TYPE_P(dat->imag) && FLOAT_ZERO_P(dat->imag)) {
/* Do nothing here */
}
else if (!k_exact_zero_p(dat->imag)) {
VALUE imag = rb_check_convert_type_with_id(dat->imag, T_RATIONAL, "Rational", idTo_r);
if (NIL_P(imag) || !k_exact_zero_p(imag)) {
rb_raise(rb_eRangeError, "can't convert %"PRIsVALUE" into Rational",
self);
}
}
return f_to_r(dat->real);
}
Returns the value of self.real as a Rational, if possible:
Example
Complex.rect(1, 0).to_r # => (1/1) Complex.rect(1, Rational(0, 1)).to_r # => (1/1) Complex.rect(1, 0.0).to_r # => (1/1)
Raises RangeError if self.imag is not exactly zero (either Integer(0) or Rational(0, _n_)) and self.imag.to_r is not exactly zero.
Related: Complex#rationalize.