I have this code:
class A
attr_accessor :count
def initialize
@count = 0
end
def increase_count
count += 1
end
end
A.new.increase_count
It complains:
in `increase_count': undefined method `+' for nil:NilClass (NoMethodError)
If I change the increase_count definition to:
class A
def increase_count
@count += 1
end
end
then it does not complain. May be I am missing something, or it is just a weird behaviour of Ruby.
A#count=requires an explicit receiver as allfoo=methods. Otherwise, the local variablecountis being created and hoisted, makingcount + 1using the local not yet initialized variable.Sidenote:
attr_accessor :countis nothing but a syntactic sugar for: