0

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!

2 Answers 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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This worked. Yes, I'm a ruby novice, I just started yesterday. I'm much more familiar with C++ and java
0

In ruby, you don't declare types:

Rational r = ...

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

1 Comment

Thanks, it worked =)! I'm new to ruby, what do you mean just write r?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.