我有点难过。请查看下面的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