Question

writing a rational class and i'm getting an error although I can't see anything wrong with my code. here is the class&relevant method:

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)

the error I get :

rational.rb:53:in `add': undefined method `Rational' for Rational:Class (NoMethodError)

thanks in advance!

Was it helpful?

Solution 2

In ruby, you don't declare types:

Rational r = ...

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

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top