Created
June 13, 2010 21:24
-
-
Save softcraft-development/437020 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Out of the box, Ruby's Rational class doesn't know how to multiply or divide a BigDecimal; | |
# You get: "TypeError: Rational can't be coerced into BigDecimal" when you try. | |
class Rational | |
alias :"old_/" :"/" | |
def /(a) | |
begin | |
# Keep existing behavior if we can | |
send(:"old_/", a) | |
rescue TypeError | |
# Note that Rational() will handle decimal denominators; it finds the appropriate integral denominator | |
Rational(self.numerator, self.denominator * a ) | |
end | |
end | |
alias :"old_*" :"*" | |
def *(a) | |
begin | |
send(:"old_*", a) | |
rescue TypeError | |
# Numerator must have gcd() (ie: be an Integer), so modify the denominator instead | |
Rational( self.numerator, self.denominator / a ) | |
end | |
end | |
end | |
class TestMathExtensions < Test::Unit::TestCase | |
def test_rational_and_bigdecimal_division | |
r = 1 / 4 | |
d = BigDecimal.new("2") | |
assert_equal (r / d), 0.125 | |
end | |
def test_rational_and_bigdecimal_multiplication | |
r = 1 / 4 | |
d = BigDecimal.new("2") | |
assert_equal (r * d), 0.5 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment