CIT 597 Assignment 9: Fractions and Unit Testing
Fall 2008, David Matuszek
Implement a Fraction class. Write tests for it.
Because this is a very short assignment, it will be worth 25 points instead of the usual 100 points.
Implement a Fraction class. It should have:
add, subtract, multiply,
and divide. Each of these should take one operand, the second
argument, and return a new fraction (for example,
f1 = f2.add(f3))).reduce! method, which uses
Euclid's
algorithm
to put a fraction into the lowest terms (it divides both the numerator
and the denominator by the gcd, Greatest Common Divisor, of the two). to_s method, for returning a string representation (for
example, "2/3") of this fraction. All fractions should automatically be kept in lowest terms. For example,
if you construct a fraction with f = Fraction.new 8, 122/3. Likewise, if you add 1/4 and
1/4, you should get 1/2. Also, there is nothing
wrong with so-called
"improper" fractions (fractions greater than 1, such as 7/3);
they are perfectly good fractions.
To keep this assignment simple, you don't have to worry about negative numbers.
Implement a FractionTest class containing unit tests
for each of the four arithmetic methods, and a test for the constructor.
You can test the constructor by testing, for example, whether Fraction.new 8, 122/3.
fractions.rb (you can put both classes into this one file).