From: Usaku NAKAMURA Date: 2011-07-12T17:49:50+09:00 Subject: [ruby-dev:44088] [Ruby 1.9 - Bug #5020][Open] Rational cannot coerce into Complex with imag. Issue #5020 has been reported by Usaku NAKAMURA. ---------------------------------------- Bug #5020: Rational cannot coerce into Complex with imag. http://redmine.ruby-lang.org/issues/5020 Author: Usaku NAKAMURA Status: Open Priority: Normal Assignee: Category: core Target version: 1.9.3 ruby -v: ruby 1.9.4dev (2011-07-11 trunk 32518) [x64-mswin64_100] とある実験をしていて気付いたのですが、虚部ありの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", -- http://redmine.ruby-lang.org