访问器方法已定义但不起作用

Accessor method is defined but does not work

我有这个代码:

class A
  attr_accessor :count

  def initialize
    @count = 0
  end

  def increase_count
    count += 1
  end
end

A.new.increase_count

它抱怨:

in `increase_count': undefined method `+' for nil:NilClass (NoMethodError)

如果我将 increase_count 定义更改为:

class A
  def increase_count
    @count += 1
  end
end

那就不抱怨了。可能是我遗漏了什么,或者这只是 Ruby.

的一种奇怪行为

A#count= 与所有 foo= 方法一样需要显式接收器。否则,正在创建和提升局部变量 count,使 count + 1 使用 尚未初始化的局部变量

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

旁注:

attr_accessor :count 只是一个语法糖:

def count
  @count
end

def count=(value)
  @count = value
end