ruby - Can't always access value of instance variable without @ even with attr_accessor -
this question has answer here:
how come error nomethoderror: undefined method '+' nil:nilclass
line puts test
prints out 1 know value 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 works if change test
@test
thought didn't have if had attr_accessor :test
when assigning value instance variable through accessor / writer, have use self
, otherwise ruby interpreter thinks local variable. in case, testfn code should this:
def testfn puts test self.test = test + 1 end
Comments
Post a Comment