Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Handle Bignum special cases in Rational#**

  • Loading branch information...
commit cd7ecb65e6fac72428d25318ead9343674c5db47 1 parent b5b10d5
@jfirebaugh jfirebaugh authored
Showing with 20 additions and 15 deletions.
  1. +20 −15 kernel/common/rational.rb
View
35 kernel/common/rational.rb
@@ -262,7 +262,20 @@ def ** (other)
den = 1
end
Rational(num, den)
- elsif other.kind_of?(Bignum) || other.kind_of?(Float)
+ elsif other.kind_of?(Bignum)
+ if self == 0
+ if other < 0
+ raise ZeroDivisionError, "divided by 0"
+ elsif other > 0
+ return Rational(0)
+ end
+ elsif self == 1
+ return Rational(1)
+ elsif self == -1
+ return Rational(other.even? ? 1 : -1)
+ end
+ Float(self) ** other
+ elsif other.kind_of?(Float)
Float(self) ** other
else
x, y = other.coerce(self)
@@ -507,8 +520,10 @@ def rationalize(eps=undefined)
end
class Fixnum
+ alias_method :power!, :"**"
+
# Returns a Rational number if the result is in fact rational (i.e. +other+ < 0).
- def rpower (other)
+ def **(other)
if other >= 0
self.power!(other)
else
@@ -518,8 +533,10 @@ def rpower (other)
end
class Bignum
+ alias_method :power!, :"**"
+
# Returns a Rational number if the result is in fact rational (i.e. +other+ < 0).
- def rpower (other)
+ def **(other)
if other >= 0
self.power!(other)
else
@@ -527,15 +544,3 @@ def rpower (other)
end
end
end
-
-unless 1.respond_to?(:power!)
- class Fixnum
- alias_method :power!, :"**"
- alias_method :"**", :rpower
- end
-
- class Bignum
- alias_method :power!, :"**"
- alias_method :"**", :rpower
- end
-end
Please sign in to comment.
Something went wrong with that request. Please try again.