Ruby private attr_writer and + = raises NoMethodError

I'm a bit stumped. See the method below add_one. When using the increment, +=the Ruby operator throws a NoMethodError. The verbal version is working fine.

private method `count=' called for #<Counter:0x007f91a480eb88 @count=0> (NoMethodError)

Why is this?

class Counter
  attr_reader :count

  def initialize
    @count = 0
  end

  def increment
    add_one
  end

private

  attr_writer :count

  def add_one
    self.count += 1          # this causes a error
    # self.count = count + 1 # this works
  end
end

c = Counter.new
puts c.count
puts c.increment
+4
source share

All Articles