Recap: Wallet
Lesson 30 of 48 in Coddy's Ruby for Java Developers course.
Challenge
EasyDefine Wallet initialized to zero. balance reads current funds. deposit(n) rejects negative amounts with ArgumentError; withdraw(n) returns false for negative or insufficient amounts without mutation, otherwise subtracts and returns true. solve reads deposit then withdrawal, outputs success and balance.
Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.
Your code goes in exercise.rb, wallet.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'wallet'
def check(value)
raise 'Public API check failed' unless value
end
w = Wallet.new; other = Wallet.new
w.deposit(8)
check(!w.withdraw(9) && w.balance == 8 && other.balance == 0)
begin; w.deposit(-2); raise "Expected rejection"; rescue ArgumentError; end
check(w.balance == 8 && w.withdraw(3) && w.balance == 5)
puts solve(STDIN.read)
All lessons in Ruby for Java Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler