vieweditattachhistoryswikistopchangessearchhelp

Ruby で BankAccount

class BankAccount
  attr :dollars, true
  def deposit(x)
    self.dollars+=x
  end
  def withdraw(x)
    self.dollars=[0, dollars-x].max
  end
  def initialize
    self.dollars=0
  end
end

account=BankAccount.new

  account.dollars=200
p account.dollars   # 200
  account.deposit 50
p account.dollars   # 250
  account.withdraw 100
p account.dollars   # 150
  account.withdraw 200
p account.dollars   # 0

class StockAccount < BankAccount
  attr :numShares, true
  attr :pricePerShare, true
  def dollars
    self.numShares  self.pricePerShare
  end
  def dollars=(x)
    self.numShares=(Float x)/self.pricePerShare
  end
  def initialize
    self.numShares=10
    self.pricePerShare=30
  end
end

stock=StockAccount.new

p stock.numShares   # 10
p stock.pricePerShare   # 30
p stock.dollars   # 300
  stock.dollars=150
p stock.numShares   # 5.0

  stock.dollars=600
p stock.dollars   # 600.0
p stock.numShares   # 20.0
  stock.deposit 60
p stock.dollars   # 660.0
p stock.numShares   # 22.0


このページを編集 (1009 bytes)


Congratulations! 以下の 3 ページから参照されています。

This page has been visited 3332 times.