The add(method) is created, but the error says it isn't

67 views Asked by At

I am at beginner level in Ruby, and an exercise I am working on requires me to create a Calculator class_ with various math methods.

Here is the code I've run, with the error. A hint I've been given in the course mentions @calc, but I don't know where or why to insert it.

 class Calculator
   attr_accessor :x, :y

   def initialize(x,y)
     @x, @y = x, y
   end

   def add()
     x + y
   end

   def subtract()   # **or should it be listed as y,x?**
     y - x
   end

   def multiply()
     x * y
   end

   def divide()
     @x.to_f / @y.to_f
   end

 end
 => nil

 calc = Calculator.new(5 , 2)
 => #<Calculator:0x00000101067258 @x=5, @y=2>

NoMethodError: undefined method `add' for #<Calculator:0x00000101067258 @x=5, @y=2>
  from (irb):32
2

There are 2 answers

0
Gupta On

As there is no any error . Only the problem is call the method with proper attributes One more things there is lot of difference between @x and a . the methods definition for add is wrong.

def add() 
  x + y 
end

instead of this rewrite this methods like

def add()
  @x + @y
end

hope it help for you .

0
lcguida On

You have two errors.

First, there's a dot after the string (outside of it) in this line:

"Performs basic mathematical operations".

Should be:

"Performs basic mathematical operations."

And the other, you have a extra end in your code. At the end of these lines:

      def divide(x,y)
        @x.to_f / @y.to_f
      end
   end
end

Should be:

  def divide(x,y)
    @x.to_f / @y.to_f
  end
end