0

How come I get the error NoMethodError: undefined method '+' for nil:NilClass but the line with puts test prints out a 1 so we know that the value is initialized?

class TestClass
  attr_accessor :test
  def initialize()
    @test = 1
  end

  def testFn
    puts test
    test = test + 1
  end
end

t = TestClass.new
t.testFn

It also works if I change test to @test but I thought I didn't have to if I had attr_accessor :test

user1136342
  • 4,731
  • 10
  • 30
  • 40

1 Answers1

1

When you are assigning value to instance variable through accessor / writer, you have to use self, otherwise Ruby interpreter thinks it is a local variable. In your case, the testFn code should look like this:

def testFn
  puts test
  self.test = test + 1
end
jan.zikan
  • 1,308
  • 10
  • 14
  • Is it common to have an attr_accessor and then only use self to assign values while just directly using the value otherwise? Or do people generally use self for both assigning and reading to make it less confusing and have less chances of missing a self? @kallax – user1136342 Sep 04 '16 at 21:42