class BankAccount def initialize(balance=0) check_balance balance @balance = balance end def withdraw(amt) if @balance < amt @balance = 0 else @balance -= amt end amt end def deposit(amt) if amt < 0 raise "Deposit amoount must be non-megative." end @balance += amt end # NOTE: if the getter was named "balance", it'd be better to use: # attr_reader :balance def get_balance @balance end def merge_accounts(account) @balance += account.get_balance() account.balance = 0 end def to_s "$#{@balance.round(2)}" end protected # NOTE: could also have the following instead of explicitly defining balance= # attr_writer :balance # Needed to set balance of object argument in merge_accounts # as a non-public method def balance= new_balance @balance = new_balance end private # NOTE: could use this for other methods that check # for non-negative values (just would be a less helpful error message) def check_balance balance if balance < 0 raise "Can't have negative balance" end end end def use_bank_accounts b1 = BankAccount.new() b2 = BankAccount.new(25.50) puts "Balance of b1: " + b1.to_s puts "Balance of b2: " + b2.to_s (b3 = BankAccount.new(3.41)).merge_accounts(b2) puts "Balance of b3: " + b3.to_s puts "Balance of b2: " + b2.to_s end