Search code examples
ruby-on-railsrubymethodsfractions

How do I fix my program which simplifies fractions


I wrote a program which adds, multiplies, subtracts, divides and simplifies fractions. When I try to simplify 2/4 it gives me 1/1. Here is the simplifying part of my program:

def simplify(numer1,denom1)
  gcd = numer1.gcd(denom1)
  final_numer = numer1 / gcd
  final_denom = numer1 / gcd

  return {"Numerator" => final_numer, "Denominator" => final_denom}
end

puts  simplify(2,4) # => 1/1

Solution

  • I think you have a typo problem here:

    def simplify(numer1,denom1)
      gcd = numer1.gcd(denom1)
      final_numer = numer1 / gcd
      final_denom = numer1 / gcd
                   #^^^^^^ shouldn't it be `denom1 / gcd` ?
      return {"Numerator" => final_numer, "Denominator" => final_denom}
    end
    

    Actually, the Rational object can easily do that:

    def simplify(numer1, denom1)
      return Rational(numer1, denom1)
    end
    

    Documentation: http://www.ruby-doc.org/core-2.0.0/Rational.html