matz / ruby-lang.org (Yukihiro Matsumoto) wrote in message news:<1050717420.142623.4191.nullmailer / picachu.netlab.jp>... > Hi, > > In message "Bug in Rational?" > on 03/04/19, "Chris Pine" <nemo / hellotree.com> writes: > > |This *can't* be right: > | > | irb(main):001:0> require 'rational' > | true > | irb(main):002:0> a = Rational.new(1,2) > | Rational(1, 2) > | irb(main):003:0> b = Rational.new(1,3) > | Rational(1, 3) > | irb(main):004:0> Rational.new(a,b) > | Rational(0, 0) > > I don't call this a bug, but a pitfall behavior. ;-) > > Rational() requires integers, so it converts rationals to integers; > thus 1/2 => 0, 1/3 => 3. I will ask Keiju about this behavior. He > might want to change. On the other hand, irb(main):001:0> require 'rational' true irb(main):002:0> a = Rational(1, 2) Rational(1, 2) irb(main):003:0> b = Rational(1, 3) Rational(1, 3) irb(main):004:0> c = Rational(a, b) NameError: undefined method `gcd' for #<Rational:0x4023837c> from /usr/local/lib/ruby/1.6/rational.rb:56:in `reduce' from /usr/local/lib/ruby/1.6/rational.rb:42:in `Rational' from (irb):4 So the Rational constructor behaves differently from Rational.new. Note also: irb(main):001:0> require 'rational' true irb(main):002:0> a = Rational.new(0, 0) Rational(0, 0) irb(main):003:0> b = Rational(0, 0) ZeroDivisionError: denominator is 0 from /usr/local/lib/ruby/1.6/rational.rb:50:in `reduce' from /usr/local/lib/ruby/1.6/rational.rb:42:in `Rational' from (irb):3 Here the Rational constructor (is that the right word?) quite properly refuses to create the non-number 0/0, but Rational.new has no such inhibitions. Regards, Bret