Lending Desk: Report
Lesson 46 of 48 in Coddy's Ruby for Java Developers course.
Challenge
EasyBuild the lending desk. Input begins with stage number 4, 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). Implement borrow(code,n): fail for missing items, negative n or insufficient stock without mutation; otherwise subtract n and return true. The borrow code n command prints its boolean. Implement give_back(code,n): fail for missing items or negative n without mutation; otherwise add n and return true. The return code n command prints its boolean. Implement report, returning all codes sorted alphabetically as code:stock pairs separated by spaces, including zero stock; empty desk returns none. The report command prints this text. 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 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