ruby-changes:65011
From: Nobuyoshi <ko1@a...>
Date: Sat, 23 Jan 2021 11:14:09 +0900 (JST)
Subject: [ruby-changes:65011] 9efd590a13 (master): Rationalize floats in coerce [Bug #17572]
https://git.ruby-lang.org/ruby.git/commit/?id=9efd590a13 From 9efd590a13d1e8b8a141c46eabb48c2a1c286d2b Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada <nobu@r...> Date: Sat, 23 Jan 2021 11:04:45 +0900 Subject: Rationalize floats in coerce [Bug #17572] --- rational.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/rational.c b/rational.c index 8548b3b..c7437df 100644 --- a/rational.c +++ b/rational.c @@ -51,6 +51,7 @@ static ID id_abs, id_integer_p, https://github.com/ruby/ruby/blob/trunk/rational.c#L51 #define f_to_s rb_obj_as_string static VALUE nurat_to_f(VALUE self); +static VALUE float_to_r(VALUE self); inline static VALUE f_add(VALUE x, VALUE y) @@ -1172,11 +1173,17 @@ nurat_coerce(VALUE self, VALUE other) https://github.com/ruby/ruby/blob/trunk/rational.c#L1173 return rb_assoc_new(other, self); } else if (RB_TYPE_P(other, T_COMPLEX)) { - if (k_exact_zero_p(RCOMPLEX(other)->imag)) - return rb_assoc_new(f_rational_new_bang1 - (CLASS_OF(self), RCOMPLEX(other)->real), self); - else + if (!k_exact_zero_p(RCOMPLEX(other)->imag)) return rb_assoc_new(other, rb_Complex(self, INT2FIX(0))); + other = RCOMPLEX(other)->real; + if (RB_FLOAT_TYPE_P(other)) { + other = float_to_r(other); + RBASIC_SET_CLASS(other, CLASS_OF(self)); + } + else { + other = f_rational_new_bang1(CLASS_OF(self), other); + } + return rb_assoc_new(other, self); } rb_raise(rb_eTypeError, "%s can't be coerced into %s", @@ -2060,7 +2067,6 @@ integer_denominator(VALUE self) https://github.com/ruby/ruby/blob/trunk/rational.c#L2067 return INT2FIX(1); } -static VALUE float_to_r(VALUE self); /* * call-seq: * flo.numerator -> integer -- cgit v1.1 -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/