Reputation: 135
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?
Upvotes: 2
Views: 1523
Reputation: 270607
Your value passed into initialize()
is a string, rather than an integer. Cast it to an int via .to_i
.
def initialize(balance)
# Cast the parameter to an integer, no matter what it receives
# and the other operators will be available to it later
@balance = balance.to_i
end
Likewise, if the parameter passed to debit()
and credit()
is a string, cast it to an int.
def credit(amount)
@balance += amount.to_i
end
def debit(amount)
@balance -= amount.to_i
end
Finally, I'll add that if you plan to set @balance
outside the initialize()
method, it is recommended to define its setter to call .to_i
implicitly.
def balance=(balance)
@balance = balance.to_i
end
Note: This assumes you want and only intend to use integer values. Use .to_f
if you need floating point values.
Upvotes: 3
Reputation: 168091
Most likely, you did
bank_account = Account.new("200")
You should actually do
bank_account = Account.new(200)
Upvotes: 3
Reputation: 15838
try with
def credit(amount)
@balance += amount.to_i
end
def debit(amount)
@balance -= amount.to_i
end
or pass a number as the parameter (the error says that you are passing a string)
Upvotes: 0