Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created November 2, 2015 18:59
Show Gist options
  • Save mayfer/aa2fcc4700ebc7b252cb to your computer and use it in GitHub Desktop.
Save mayfer/aa2fcc4700ebc7b252cb to your computer and use it in GitHub Desktop.
class NotEnoughCashError < Exception
end
class Bank
attr_reader :accounts
attr_reader :name
def initialize(name)
@name = name
@accounts = []
end
def add_accounts(accounts)
@accounts.concat(accounts)
end
def num_chequing_accounts
@accounts.select { |acc| acc.class.name=="ChequingAccount" }.length
end
def transfer(from_account, to_account, amount)
begin
from_account.withdraw(amount)
to_account.deposit(amount)
rescue NotEnoughCashError => e
puts e
end
end
end
class Account
attr_accessor :owner, :balance
def initialize(owner, balance)
@owner = owner
@balance = balance
end
# instance or class?
def self.create_accounts(owner)
s = SavingsAccount.new(owner, 0)
c = ChequingAccount.new(owner, 0)
[s, c]
end
def withdraw(amount)
self.balance -= amount
end
def deposit(amount)
self.balance += amount
end
end
class SavingsAccount < Account
@@num_savings_accounts = 0
def initialize(name, balance)
super
@@num_savings_accounts += 1
end
end
class ChequingAccount < Account
@@num_chequing_accounts = 0
def initialize(name, balance)
super
@@num_chequing_accounts += 1
end
# instance method
def withdraw(amount)
if self.balance - amount < 50
raise NotEnoughCashError, "Chequing Accounts must have at least $50 at all times"
else
self.balance -= amount
end
end
end
bank = Bank.new("Bank of Rob Ford")
accounts = Account.create_accounts("murat")
bank.add_accounts(accounts)
account = ChequingAccount.new("me", 0)
account2 = SavingsAccount.new("not mee", 200)
bank.transfer(account, account2, 50)
# assigning to a new variable name does not change memory address
account3 = account
puts "arrived at end of file"
def something(arg1, arg2)
end
begin
something("just one arg")
456/0 # ZeroDivisionError
lol # NameError
rescue ZeroDivisionError => e
puts "tried dividing by zero"
rescue NameError => e
puts "gracefully handling error"
puts e
rescue Exception => e # catchall
puts "caught generic exception"
puts e
end
puts "reached end of file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment