Ruby private attr_writer and += causes NoMethodError

66 views Asked by At

I'm a bit stumped. Take a look at the add_one method below. When using the increment += operator Ruby throws a NoMethodError. The verbose version works 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
0

There are 0 answers