I have this class:
class Account
attr_accessor :balance
def initialize(balance)
@balance = balance
end
def credit(amount)
@balance += amount
end
def debit(amount)
@balance -= amount
end
end
Then, for example, later in the program:
bank_account = Account.new(200)
bank_account.debit(100)
If I call the debit method with the “-=” operator in it (as shown in the class above) the program fails with the following message:
bank2.rb:14:in `debit': undefined method `-' for "200":String (NoMethodError)
from bank2.rb:52:in `<main>'
But if I remove the minus sign and just make it @balance = amount, then it works. Obviously I want it to subtract, but I can’t figure out why it doesn’t work. Can math not be done with instance variables?
Your value passed into
initialize()is a string, rather than an integer. Cast it to an int via.to_i.Likewise, if the parameter passed to
debit()andcredit()is a string, cast it to an int.Finally, I’ll add that if you plan to set
@balanceoutside theinitialize()method, it is recommended to define its setter to call.to_iimplicitly.Note: This assumes you want and only intend to use integer values. Use
.to_fif you need floating point values.