基本的Ruby问题

时间:2015-05-20 22:35:08

标签: ruby

我的理解是checkingsavings保存在account_aaccount_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的价值?

2 个答案:

答案 0 :(得分:0)

使用trans创建Transaction.new时,对checkingsavings的引用将存储在事务对象中@account_a@account_b < / p>

transfer方法使用debit调用@account_a,使用credit调用@account_b,以便将a的余额减少一定数量并增加余额b相同的金额,实际上是从支票转为储蓄。

答案 1 :(得分:0)

在倒数第二行,您正在将新的交易从checking帐户初始化为savings帐户。然后在最后一行,您将转移50。

您无法打印trans的值,因为没有与之关联的值。您可以通过致电savings.balancechecking.balance

打印已初始化帐户的余额