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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With