Menu
CoddyTech

Registro bancario

Fa parte della sezione Programmazione orientata agli oggetti del percorso Ruby di Coddy. Lezione 57 di 57.

challenge icon

Sfida

Difficile

Crea una piccola banca. BankError < StandardError è la classe genitrice di InvalidAmount, InsufficientFunds, LimitReached e NoAccount, che restituiscono i messaggi invalid amount, insufficient funds in 2, withdrawal limit on 2 e no account 9. Account.new(id, owner) ha i getter per id, owner e balance, e un setter privato per il saldo. deposit(amount) e withdraw(amount) sollevano InvalidAmount se il valore è inferiore a 1; withdraw solleva InsufficientFunds quando il saldo scenderebbe sotto lowest_balance, un metodo hook che restituisce 0. month_end non fa nulla e kind restituisce il tipo di conto. Checking consente uno scoperto fino a -100. Savings consente al massimo 2 prelievi al mese (LimitReached) e il suo month_end aggiunge l'1% di interesse, arrotondato per difetto, e azzera il conteggio. to_s restituisce 1 ada checking: -20. Bank#open(kind, id, owner) crea un conto Checking o Savings, account(id) solleva NoAccount, transfer(from, to, amount) cerca entrambi i conti prima di prelevare e depositare, month_end lo chiama su ogni conto e Bank include Enumerable, con each che restituisce i conti in ordine di id.

Il codice fornito legge comandi come open checking 1 ada, dep 1 100, wd 2 30, tr 1 2 50 o month, stampa ok o il messaggio di errore per ciascuno e infine stampa tutti i conti.

Il tuo codice va inserito in bank_error.rb, invalid_amount.rb, insufficient_funds.rb, limit_reached.rb, no_account.rb, account.rb, checking.rb, savings.rb e bank.rb. main.rb contiene il codice fornito per l'input/output e non può essere modificato.

Provalo tu

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'

# Codice di input/output fornito: lascialo così com'è
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 }

Tutte le lezioni di Programmazione orientata agli oggetti

Esercitati da solo: Compilatore Ruby online