Ruby private attr_writer和+ =导致NoMethodError

时间:2014-11-26 11:37:13

标签: ruby private-methods

我有点难过。请查看下面的add_one方法。使用增量+=运算符时,Ruby会抛出NoMethodError。详细版本工作正常。

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

为什么会这样?

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 个答案:

没有答案