我的理解是checking
和savings
保存在account_a
和account_b
下。有人可以解释最后两行中发生的事情吗?
class Account
attr_accessor :balance
def initialize(balance)
@balance = balance
end
end
class Transaction
def initialize(account_a,account_b)
@account_a = account_a
@account_b = account_b
end
private
def debit(account, amount)
account.balance -= amount
end
def credit(account,amount)
account.balance += amount
end
public
def transfer(amount)
debit(@account_a, amount)
credit(@account_b, amount)
end
end
savings = Account.new (100)
checking = Account.new (200)
trans = Transaction.new(checking, savings)
trans.transfer(50)
如何打印trans
的价值?
答案 0 :(得分:0)
在倒数第二行,您正在将新的交易从checking
帐户初始化为savings
帐户。然后在最后一行,您将转移50。
您无法打印trans的值,因为没有与之关联的值。您可以通过致电savings.balance
和checking.balance
答案 1 :(得分:0)
使用trans
创建Transaction.new
时,对checking
和savings
的引用将存储在事务对象中@account_a
和@account_b
< / p>
transfer
方法使用debit
调用@account_a
,使用credit
调用@account_b
,以便将a
的余额减少一定数量并增加余额b
相同的金额,实际上是从支票转为储蓄。