Fraction Assignment
Your assignment: Complete the Fraction class (with unit tests).
- Provide methods to add, subtract, multiply, divide, and invert fractions
- Example: new_fraction = fraction_1.multiply fraction_2
- All fractions should be stored in a normalized form
- If the fraction is negative, only the numerator should be negative
- If the fraction is positive, the numerator and denominator should both be positive
- If the fraction is zero, it should be stored as 0/1
- Zero is never a legal denominator
- Provide complete unit tests for all (nonprivate) methods
Starter code follows...
fraction.rb
class Fraction
attr_reader :numerator, :denominator
def initialize numerator, denominator
throw Exception.new("Illegal zero denominator") if denominator == 0
@numerator = numerator
@denominator = denominator
reduce
end
def to_s
@numerator.to_s + '/' + @denominator.to_s
end
def == other # Yes, I'm redefining ==
@numerator == other.numerator and @denominator == other.denominator
true
end
private
def reduce
n, d = @numerator, @denominator
while n != d
if n > d
n -= d
else
d -= n
end
end
@numerator /= n
@denominator /= n
end
end
test_fraction.rb
require 'Fraction'
class TestFraction < Test::Unit::TestCase
@@f_3_4 = Fraction.new(3, 4)
def setup
# Stuff to be done before each test method
end
def teardown
# Stuff to be done after each test method
end
def test_new
assert_equal(@@f_3_4, Fraction.new(3, 4))
assert_equal(@@f_3_4, Fraction.new(30, 40))
# Negative numbers may cause an infinite loop
# assert_equal(@@f_3_4, Fraction.new(-3, -4))
end
end