Menu
CoddyTech

Ruby 재고 프로그램 포팅하기

Coddy의 Ruby 개발자를 위한 Lua 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

중급

이 완전한 Ruby 프로그램을 Lua 모듈로 포팅하세요. 각 입력 줄은 소문자 ASCII 이름, 콜론, 부호가 있는 정수 델타로 이루어집니다. 모든 줄은 올바른 형식이며 수량과 중간 합계는 Lua 숫자 표현의 정확한 정수 범위 내에 있습니다. 필터링하기 전에 모든 업데이트를 집계하세요. 최종 합계가 양수인 항목은 이름의 오름차순으로 name=total 형식으로 반환하고 쉼표로 연결하세요. 해당 항목이 없으면 empty를 반환하세요. inventory.aggregate(lines)는 합산된 모든 델타를 담은 새 테이블을 반환해야 하며, 합계가 0인 항목도 유지해야 합니다. 편집 가능한 앱은 이 테이블을 형식에 맞게 출력하고 필터링합니다. 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는 stdin을 읽어 줄 목록을 만들고, 공개 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 컴파일러