Menu
CoddyTech

银行账簿

本课属于 Coddy Ruby 学习旅程的“面向对象编程”单元。第 57 课,共 57 课。

challenge icon

挑战

困难

创建一个小型银行。BankError < StandardError 是 InvalidAmount、InsufficientFunds、LimitReached 和 NoAccount 的父类,它们分别携带消息 invalid amount、insufficient funds in 2、withdrawal limit on 2 和 no account 9。Account.new(id, owner) 为 id、owner 和 balance 提供读取器,并为余额提供私有设置器。deposit(amount) 和 withdraw(amount) 在金额小于 1 时引发 InvalidAmount;当余额会低于 lowest_balance 时,withdraw 会引发 InsufficientFunds,这个钩子会返回 0。month_end 不执行任何操作,kind 返回账户类型。Checking 允许透支至 -100。Savings 每月最多允许取款 2 次(LimitReached),其 month_end 会添加 1% 的利息,向下取整,并重置计数。to_s 返回 1 ada checking: -20。Bank#open(kind, id, owner) 会创建一个 Checking 或 Savings,account(id) 会引发 NoAccount,transfer(from, to, amount) 会先查找两个账户,再取款和存款,month_end 会对每个账户调用它,而 Bank 会包含 Enumerable,并由 each 按账户 ID 顺序逐个返回账户。

提供的代码会读取命令 open checking 1 ada、dep 1 100、wd 2 30、tr 1 2 50 或 month,对每条命令输出 ok 或错误消息,最后输出所有账户。

你的代码应写在 bank_error.rb、invalid_amount.rb、insufficient_funds.rb、limit_reached.rb、no_account.rb、account.rb、checking.rb、savings.rb 和 bank.rb 中。main.rb 包含提供的输入和输出代码,不能编辑。

亲手试试

require_relative 'bank_error'
require_relative 'invalid_amount'
require_relative 'insufficient_funds'
require_relative 'limit_reached'
require_relative 'no_account'
require_relative 'account'
require_relative 'checking'
require_relative 'savings'
require_relative 'bank'

# 提供的输入/输出代码:保持原样
input = []
while (line = gets)
  input << line.chomp
end
bank = Bank.new
input.each do |cmd|
  parts = cmd.split
  begin
    case parts[0]
    when "open" then bank.open(parts[1], parts[2].to_i, parts[3])
    when "dep" then bank.account(parts[1].to_i).deposit(parts[2].to_i)
    when "wd" then bank.account(parts[1].to_i).withdraw(parts[2].to_i)
    when "tr" then bank.transfer(parts[1].to_i, parts[2].to_i, parts[3].to_i)
    else bank.month_end
    end
    puts "ok"
  rescue BankError => e
    puts e.message
  end
end
bank.each { |account| puts account }

面向对象编程中的所有课

自己练习: Ruby 在线编译器