如何修复简化分数的程序

时间:2013-10-21 20:57:24

标签: ruby-on-rails ruby methods fractions

我写了一个程序,它可以对分数进行加法,乘法,减法,除法和简化。当我尝试简化2/4时,它给了我1/1。这是我的程序的简化部分:

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

1 个答案:

答案 0 :(得分:2)

我认为你这里有拼写错误问题:

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

实际上,Rational对象可以很容易地做到这一点:

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

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