1

我一直在谷歌和堆栈溢出,我似乎找不到答案。

我需要“bookman”函数来查找“cash”的实例,以便它可以调用现金的方法。

我怎样才能做到这一点?

谢谢!

这是我的代码

class Account
  def initialize (deb_bal, cred_bal)
    @deb_bal = deb_bal
    @cred_bal = cred_bal
  end

  def debit(x)
    @deb_bal += x
  end

  def credit(x)
   @cred_bal += x
  end

  def balance
    bal = @deb_bal.to_i - @cred_bal.to_i
    if  bal < 0
      puts "Credit Balance of #{bal.abs}"
    else
      puts "Debit Balance of #{bal.abs}"
    end
  end
end

def bookman 

end

cash = Account.new(0,0)
#acts_rec = Account.new

cash.credit 100
bookman
4

2 回答 2

2

您可以cash作为参数传递给bookman函数,也可以创建cash一个实例变量。

于 2012-04-20T07:43:52.330 回答
2

您可以将对象传递给方法:

...
def bookman(acct)
  acct.debit(50)
end

cash = Account.new(0, 0)
cash.credit 100
bookman(cash)
cash.balance

=> Credit Balance of 50
于 2012-04-20T07:45:49.697 回答