Project

General

Profile

Actions

Bug #5020

closed

Rational cannot coerce into Complex with imag.

Added by usa (Usaku NAKAMURA) over 12 years ago. Updated over 12 years ago.

Status:
Closed
Target version:
ruby -v:
ruby 1.9.4dev (2011-07-11 trunk 32518) [x64-mswin64_100]
Backport:
[ruby-dev:44088]

Description

とある実験をしていて気付いたのですが、虚部ありのComplexを引数としてRational#coerceを呼ぶとTypeErrorが発生します。

Rational(1,2).coerce(Complex(1,1)) #=> TypeError

虚部がなければ問題ありません。ちなみに結果はRationalになります。

Rational(1,2).coerce(Complex(1,0)) #=> [(1/1), (1/2)]

一方で、レシーバと引数をひっくり返すと、Complex側に虚部があってもなくてもcoerceできます。ちなみに結果はComplexになります。

Complex(1,0).coerce(Rational(1,2)) #=> [((1/2)+0i), (1+0i)]
Complex(1,1).coerce(Rational(1,2)) #=> [((1/2)+0i), (1+1i)]

Rational#coerce(aComplex)でaComplexに虚部がない時にRationalな結果を返すことについては意見はないのですが、虚部があるときにTypeErrorになるのはバグだと思います。
いかがでしょうか?

Index: rational.c

--- rational.c (revision 32520)
+++ rational.c (working copy)
@@ -1108,6 +1108,8 @@ nurat_coerce(VALUE self, VALUE other)
if (k_exact_zero_p(RCOMPLEX(other)->imag))
return rb_assoc_new(f_rational_new_bang1
(CLASS_OF(self), RCOMPLEX(other)->real), self);

  • else

  •   return rb_assoc_new(other, rb_Complex(self, INT2FIX(0)));
    

    }

    rb_raise(rb_eTypeError, "%s can't be coerced into %s",

Actions

Also available in: Atom PDF

Like0
Like0Like0