Port Ruby Room Objects
Lesson 48 of 48 in Coddy's Lua for Ruby Developers course.
Challenge
MediumPort this complete Ruby program into Lua modules. The first line is a nonnegative room capacity; remaining lines are signed integer reservation requests. Accept only strictly positive requests that fit. A failed request must leave used seats unchanged. Return remaining:accepted. Model.new(capacity) exposes capacity and used, initially zero; Model:reserve(seats) returns a boolean and mutates only on success. Separate rooms must be independent. Transfer Ruby instance-variable invariants to explicit Lua table state.
Ruby room reference
class Room
attr_reader :capacity, :used
def initialize(capacity)
@capacity = capacity
@used = 0
end
def reserve(seats)
return false if seats <= 0 || @used + seats > @capacity
@used += seats
true
end
end
lines = STDIN.read.lines.map(&:chomp)
room = Room.new(Integer(lines.shift, 10))
accepted = lines.count { |line| room.reserve(Integer(line, 10)) }
puts "#{room.capacity - room.used}:#{accepted}"Edit app.lua and model.lua. The visible locked main.lua reads stdin into lines, checks the public API, calls app.run(lines), and prints one returned value with a final newline. Do not print diagnostics. Input is nonempty for the room task; inventory input may be empty.
Try it yourself
-- Public API checks
do
local Model=require("model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
All lessons in Lua for Ruby Developers
1From Ruby to Lua
Run Lua Modulesputs to printRuby Locals and Lua ScopeRuby Integer to Lua NumberStrings as Byte SequencesRecap: Format a Receipt4Methods, Functions, Closures
Methods to FunctionsKeyword Defaults to OptionsTuples to Multiple ResultsBlocks and Captured LocalsRecap: Pricing Functions2Values and Decisions
nil Values and Missing FieldsShared Truth Ruleselsif to elseifRuby == and Table IdentityRecap: Admission Rules5Arrays and Hashes to Tables
Arrays to Dense TablesHash Records and pairsSet Membership with Keysdup and Table CopiesRecap: Count InventoryPractice on your own: Online Lua compiler