gpt4 book ai didi

ruby - 带有实例变量的数学

转载 作者:数据小太阳 更新时间:2023-10-29 08:28:10 25 4
gpt4 key购买 nike

我有这门课:

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,那么它就可以工作了。显然我想让它减去,但我不明白为什么它不起作用。数学不能用实例变量来完成吗?

最佳答案

您传递给 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

最后补充一点,如果打算在initialize()方法外设置@balance,建议定义其setter调用 .to_i 隐含地。

def balance=(balance)
@balance = balance.to_i
end

注意:这假设您想要并且只打算使用整数值。如果您需要浮点值,请使用 .to_f

关于ruby - 带有实例变量的数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com