Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method `+' for nil:NilClass (NoMethodError)

Tags:

ruby

I'm writing a simple class that is initialized with a variable called "cash" which is an integer.

Below is the code. When I run this, I get the NoMethodError. I know I can easily fix this by referencing the local class variable with @cash, but a book I read on OOP recommend to almost never use the @, and instead set the attr and use simply 'cash'. I have set attr_accessor, but it doesn't work, and I'd like to understand why. Thanks

class Person
  attr_accessor :cash

  def initialize(cash)
    @cash = cash
  end

  def add_cash(amount)
    cash = cash + amount
  end
end
like image 219
user91240192094 Avatar asked May 09 '26 04:05

user91240192094


1 Answers

Local variable reference has precedence over method call with the same name.

Similarly, local variable assignment has precedence over method call with the same name. A writer method of the form foo= needs an explicit receiver. When the receiver is omitted, it is not recognized as a method, but as a local variable assignment.

def add_cash(amount)
  self.cash = cash + amount
end
like image 96
sawa Avatar answered May 11 '26 19:05

sawa