即使使用attr_accessor,也无法在不使用@的情况下访问实例变量的值

时间:2016-08-24 00:23:53

标签: ruby

为什么我收到错误NoMethodError: undefined method '+' for nil:NilClass,但puts test行打印出1,所以我们知道该值已初始化?

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

  def testFn
    puts test
    test = test + 1
  end
end

t = TestClass.new
t.testFn

如果我将test更改为@test,它也会有效但我认为如果我有attr_accessor :test

我就不会这样做

1 个答案:

答案 0 :(得分:1)

当您通过访问器/编写器为实例变量赋值时,必须使用self,否则Ruby解释器会认为它是局部变量。在您的情况下,testFn代码应如下所示:

def testFn
  puts test
  self.test = test + 1
end
相关问题