## Bug #5178

### Complex#rationalize should rationalize

**Description**

Complex#rationalize currently calls `to_r`

on the real part instead of `rationalize`

:

f = 1/3.0

c = Complex(f)

c.to_r == f.to_r # => true

c.rationalize == f.rationalize # => false

Should I not commit this to 1.9.3 too?

diff --git a/complex.c b/complex.c

index 78f0902..1b76074 100644

--- a/complex.c

+++ b/complex.c

@@ -1335,7 +1335,8 @@ nucomp_to_f(VALUE self)

- call-seq:
- cmp.to_r -> rational
*
- * Returns the value as a rational if possible.
- * If the imaginary part is exactly 0, returns the real part as a Rational,
- * otherwise a RangeError is raised. */ static VALUE nucomp_to_r(VALUE self) @@ -1354,14 +1355,22 @@ nucomp_to_r(VALUE self)

- call-seq:
- cmp.rationalize([eps]) -> rational
*
- * Returns the value as a rational if possible. An optional argument
- * eps is always ignored.
- * If the imaginary part is exactly 0, returns the real part as a Rational,
- * otherwise a RangeError is raised. */ static VALUE nucomp_rationalize(int argc, VALUE *argv, VALUE self) {
- get_dat1(self); + rb_scan_args(argc, argv, "01", NULL);
- return nucomp_to_r(self); +
- if (k_inexact_p(dat->imag) || f_nonzero_p(dat->imag)) {
- VALUE s = f_to_s(self);
- rb_raise(rb_eRangeError, "can't convert %s into Rational",
- StringValuePtr(s));
- }
- return rb_funcall(dat->real, rb_intern("rationalize"), argc, argv); }

#### Updated by mrkn (Kenta Murata) over 8 years ago

**Status**changed from*Open*to*Closed***% Done**changed from*0*to*100*

This issue was solved with changeset r32903.

Marc-Andre, thank you for reporting this issue.

Your contribution to Ruby is greatly appreciated.

May Ruby be with you.

- complex.c (nucomp_rationalize): calls rationalize of real part if imaginary part is exactly zero. The patch is made by Marc-Andre Lafortune. fixes [Bug #5178] [ruby-core:38885]
- test/ruby/test_complex.rb (test_rationalize): add a test for the above change.
- complex.c (nucomp_to_r): fix RDoc comment. The patch is made by Marc-Andre Lafortune.