Lending Desk: Catalog
Lesson 43 of 48 in Coddy's Ruby for PHP Developers course.
Build one lending desk across four stages: catalog, borrowing, returns and reporting. Keep each type in its own file. Later stages start with the preceding solution and use the same locked driver.
Challenge
EasyBuild the lending desk. Input begins with stage number 1, then one command per line. Codes are single lowercase words; initial stocks are nonnegative integers. Implement Item(code,stock) with code reader and stock reader/writer. Desk starts empty; add(code,stock) returns false for duplicate codes without replacing stock, otherwise stores an Item and returns true. stock(code) returns its quantity or nil if absent. Commands add code n and stock code print their results (missing for nil). Return one output line per command, or none for no commands. Earlier behavior must remain correct.
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, item.rb, desk.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'exercise'
require_relative 'item'
require_relative 'desk'
def check(value)
raise 'Public API check failed' unless value
end
input = STDIN.read
stage = input.split.first.to_i
item = Item.new('probe', 3)
check(item.code == 'probe' && item.stock == 3)
desk = Desk.new
check(desk.add('x', 2) && !desk.add('x', 9))
check(desk.stock('x') == 2 && desk.stock('missing').nil?)
if stage >= 2
check(desk.borrow('x', 1) && desk.stock('x') == 1)
check(!desk.borrow('x', 2) && !desk.borrow('missing', 1) && !desk.borrow('x', -1))
check(desk.stock('x') == 1)
end
if stage >= 3
check(desk.give_back('x', 4) && desk.stock('x') == 5)
check(!desk.give_back('absent', 2) && !desk.give_back('x', -2))
check(desk.stock('x') == 5)
end
if stage >= 4
desk.add('a', 0)
check(desk.report == 'a:0 x:5')
check(Desk.new.report == 'none')
end
puts solve(input)
All lessons in Ruby for PHP 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