rubyattr-accessor

Accessor method is defined but does not work


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.


Solution

  • A#count= requires an explicit receiver as all foo= methods. Otherwise, the local variable count is being created and hoisted, making count + 1 using the local not yet initialized variable.

    class A
      attr_accessor :count
      def initialize
        @count = 0
      end
    
      def increase_count
      # ⇓⇓⇓⇓⇓ THIS 
        self.count += 1
      end
    end
    
    puts A.new.increase_count   
    #⇒ 1
    

    Sidenote:

    attr_accessor :count is nothing but a syntactic sugar for:

    def count
      @count
    end
    
    def count=(value)
      @count = value
    end