0

I have the following class defined

class MyClass
 attr_accessor :my_var
 def initialize
  @my_var = 0
 end

  def increment
    my_var = my_var + 1
  end
end

But if I run:

myObj = MyClass.new
puts myObj.increment # should output: 1

Ruby gives an error, although the expected output should be 1

ERROR MSG:

undefined method `+' for nil:NilClass (NoMethodError)

EDIT: The main question is, what is this line doing: my_var = my_var + 1

Is it invoking the setter method? Or is it trying to assign a local variable? In either case, why would it give the error msg it gives?

Sida Zhou
  • 3,529
  • 2
  • 33
  • 48

0 Answers0