Tuesday, January 25, 2011

Ruby and Rational Numbers

Here's a problem over on Programming Praxis that for whatever reason I wasn't having much luck posting there. Their loss, your gain ;-). Here's the code ...


class Fraction

attr_reader :n, :d

def initialize(n, d)
raise "Can't have zero denominator." if d == 0

n, d = -n, -d if d < 0

g = n.gcd(d)
if g == 1
@n = n
@d = d
else
@n = n / g
@d = n / g
end
end

def plus(f)
Fraction.new((@n*f.d)+(@d*f.n), @d*f.d)
end

def minus(f)
Fraction.new((@n*f.d)-(@d*f.n), @d*f.d)
end

def times(f)
Fraction.new(@n*f.n, @d*f.d)
end

def divide(f)
Fraction.new(@n*f.d, @d*f.n)
end

def to_s
"#{@n}/#{@d}"
end
end

f1 = Fraction.new(1, 3)
f2 = Fraction.new(-1, 7)
puts "#{f1} + #{f2} = #{f1.plus(f2)}"
puts "#{f1} + #{f2} = #{f1.minus(f2)}"
puts "#{f1} + #{f2} = #{f1.times(f2)}"
puts "#{f1} + #{f2} = #{f1.divide(f2)}"


Nothing too awfully complex here, but if you have questions, let me know.

No comments:

Post a Comment