Menu
CoddyTech

Recap: Wallet

Lesson 30 of 48 in Coddy's Ruby for Python Developers course.

challenge icon

Challenge

Easy

Define 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 Python Developers

Practice on your own: Online Ruby compiler