未定义的方法`+' for nil:NilClass(NoMethodError)

时间:2014-10-26 01:25:21

标签: ruby

我正在编写一个简单的类,该类使用名为“cash”的变量进行初始化,该变量是一个整数。

以下是代码。当我运行它时,我得到NoM​​ethodError。我知道我可以通过使用@cash引用本地类变量来轻松解决这个问题,但我在OOP上阅读的一本书建议几乎不要使用@,而是设置attr并使用'cash'。我已经设置了attr_accessor,但它不起作用,我想了解原因。感谢

class Person
  attr_accessor :cash

  def initialize(cash)
    @cash = cash
  end

  def add_cash(amount)
    cash = cash + amount
  end
end

3 个答案:

答案 0 :(得分:4)

局部变量引用优先于具有相同名称的方法调用。

类似地,局部变量赋值优先于具有相同名称的方法调用。 foo=形式的编写器方法需要一个明确的接收器。当省略接收器时,它不被识别为方法,而是作为局部变量赋值。

def add_cash(amount)
  self.cash = cash + amount
end

答案 1 :(得分:0)

add_cash方法更改为:

  def add_cash(amount)
    @cash = cash + amount  # using cash= will define a local variable in the method,
                           # then cash + amount will become nil + amount
                           # or you could use self.cash instead of @cash
  end

<强>更新

您可以进行以下比较:

  def add_cash_local(amount)
    puts "Instance cash: #{cash}"    # we can use cash for the same effect of self.cash or @cash                  
                                     # If there is no local variable assigned as cash
    puts "Instance cash + amount: #{cash + amount}"

    cash = 100
    puts "Local cash: #{cash}"       # after cash= assignment, cash is differ from self.cash or @cash
    puts "Local cash + amount: #{cash + amount}"

    puts "Instance cash: #{@cash}"
    puts "Instance cash + amount: #{@cash + amount}"

    puts "Instance cash: #{self.cash}"
    puts "Instance cash + amount: #{self.cash + amount}"

  end

答案 2 :(得分:-1)

错误应该是(为什么你得到' - ',我不知道,除非你没有显示你的所有代码和你的方法调用):

未定义的方法`+'代表nil:NilClass(NoMethodError)

代码中的错误源于现金变量只是局部变量的事实。在调用add_amount之前未定义,因此您将错误视为nil:NilClass。

attr_accessor的文档中,即为实例(@cash)变量创建set和get方法。因此,在声明类时,需要将参数作为实例变量引用。