我有这堂课:
class Account
attr_accessor :balance
def initialize(balance)
@balance = balance
end
def credit(amount)
@balance += amount
end
def debit(amount)
@balance -= amount
end
end
然后,例如,稍后在程序中:
bank_account = Account.new(200)
bank_account.debit(100)
如果我使用“ - =”运算符调用借记方法(如上面所示),程序将失败并显示以下消息:
bank2.rb:14:in `debit': undefined method `-' for "200":String (NoMethodError)
from bank2.rb:52:in `<main>'
但如果我删除减号并将其设为@balance = amount,那么它就可以了。显然我希望它减去,但我无法弄清楚为什么它不起作用。数学不能用实例变量来完成吗?
答案 0 :(得分:3)
传递给initialize()
的值是一个字符串,而不是整数。通过.to_i
将其转换为int。
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
同样,如果传递给debit()
和credit()
的参数是一个字符串,则将其强制转换为int。
def credit(amount)
@balance += amount.to_i
end
def debit(amount)
@balance -= amount.to_i
end
最后,我要补充一点,如果您打算在@balance
方法之外设置initialize()
,建议您定义其setter以隐式调用.to_i
。
def balance=(balance)
@balance = balance.to_i
end
注意:这假定您想要并且只打算使用整数值。如果需要浮点值,请使用.to_f
。
答案 1 :(得分:3)
最有可能的是,你做了
bank_account = Account.new("200")
你应该真的这样做
bank_account = Account.new(200)
答案 2 :(得分:0)
尝试
def credit(amount)
@balance += amount.to_i
end
def debit(amount)
@balance -= amount.to_i
end
或传递一个数字作为参数(错误表明您正在传递一个字符串)