Menu
CoddyTech

Lending Desk: Catalog

Lesson 43 of 48 in Coddy's Ruby for Java 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 icon

Challenge

Easy

Build 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 Java Developers

Practice on your own: Online Ruby compiler