0

编写一个理性的类,虽然我看不出我的代码有什么问题,但我得到了一个错误。这是类&相关方法:

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)

提前致谢!

4

2 回答 2

1

Are you coming from Java? In ruby you don't have to specify variable type in declaration

Rational r = Rational.new(r1.numerator + r2.numerator, r1.denominator)

should be

r = Rational.new(r1.numerator + r2.numerator, r1.denominator)
于 2013-09-17T06:05:22.660 回答
0

In ruby, you don't declare types:

Rational r = ...

Wrong! Ruby interprets that as the method call Rational() with the argument r.

于 2013-09-17T06:05:24.840 回答