V.Abhijith Bharadwaj V.Abhijith Bharadwaj - 5 months ago 7
Ruby Question

Ruby beginner needs a hand

I am a beginner in ruby.

I've tried to run this code and it shows run time error.

What's wrong with this code?

class Calc
attr_accessor :val1, :val2
def initialize (val1,val2)
@val1=val1
@val2=val2
end
end
a=Calc.new(2,3)
a.add_two_numbers(3)

def add_two_numbers(v3)
return @val1+@val2+v3
end

Answer

The method add_two_numbers is not defined on the class Calc, however you are using it as if it is. This is the problem.

I would presume you got a NoMethodError.

Update: As pointed out in the comments, in actuallity, the method is defined on the Object class by default, which then gets auto inherited into all classes, but as private. This actually means that you will be getting the error saying that a private method is being called. The fix remains the same, since the overarching problem is a confusion in how to define classes and their methods.

The fix would be to define the method on the class, by putting it in the class body.

class Calc
  attr_accessor :val1, :val2
  def initialize (val1,val2)
    @val1=val1
    @val2=val2
  end

  def add_two_numbers(v3)
    return @val1+@val2+v3
  end
end
Comments