Menu
CoddyTech

移植 Ruby 库存管理程序

Coddy 面向 Ruby 开发者的 Lua 课程的第 47 课,共 48 课。

challenge icon

挑战

中等

将这个完整的 Ruby 程序移植为 Lua 模块。每行输入都包含一个小写 ASCII 名称、一个冒号和一个带符号的整数增量。所有行的格式都正确,数量和中间总和都在 Lua 数字表示的精确整数范围内。筛选前先汇总所有更新。将最终总和为正数的项按名称升序排列,格式为 name=total,并用逗号连接;如果没有符合条件的项,则返回 empty。inventory.aggregate(lines) 必须返回一个包含所有增量总和的新表,并保留总和为零的项。可编辑的 app 会对该表进行格式化和筛选。与 Ruby 的 Hash 迭代不同,Lua 的 pairs 不保证按插入顺序遍历;请显式对名称排序。

Ruby 库存参考

def aggregate(lines)
  counts = Hash.new(0)
  lines.each do |line|
    name, amount = line.split(":", 2)
    counts[name] += Integer(amount, 10)
  end
  counts
end
counts = aggregate(STDIN.read.lines.map(&:chomp))
rows = counts.keys.sort.select { |name| counts[name] > 0 }
  .map { |name| "#{name}=#{counts[name]}" }
puts(rows.empty? ? "empty" : rows.join(","))

编辑 app.lua 和 inventory.lua。可见且锁定的 main.lua 会将标准输入读入各行,检查公开 API,调用 app.run(lines),并以末尾换行符打印一个返回值。不要打印诊断信息。本题的输入非空;库存输入可能为空。

亲手试试

-- 公共 API 检查
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

面向 Ruby 开发者的 Lua中的所有课

自己练习: Lua 在线编译器