写一个理性的类,我收到一个错误,虽然我看不出我的代码有什么问题。这是课堂和相关方法:
class Rational
attr_reader :numerator, :denominator
def initialize(numerator=1,denominator=1)
@numerator = numerator
@denominator = denominator
reduce
end
class << self
def lcd(r1,r2)
...
...
end
def add(r1,r2)
if r1.denominator != r2.denominator
lcd(r1,r2)
end
Rational r = Rational.new(r1.numerator + r2.numerator, r1.denominator)
r1.reduce
r2.reduce
return r
end
end
r = Rational.new
r2 = Rational.new(1,3)
r3 = Rational.new(1,4)
r = Rational.add(r2,r3)
我得到的错误:
rational.rb:53:in `add': undefined method `Rational' for Rational:Class (NoMethodError)
提前感谢!
答案 0 :(得分:1)
你是来自Java吗?在ruby中,您不必在声明中指定变量类型
Rational r = Rational.new(r1.numerator + r2.numerator, r1.denominator)
应该是
r = Rational.new(r1.numerator + r2.numerator, r1.denominator)
答案 1 :(得分:0)
在ruby中,您不会声明类型:
Rational r = ...
错误! Ruby解释为方法使用参数r。
调用Rational()