Ensure 与清理
Coddy 面向 Luau 开发者的 Ruby 课程的第 24 课,共 48 课。
Luau 的 pcall 或 xpcall 可以保护代码运行,但没有像 Ruby 那样通用的 ensure 语句。请在受保护的调用之后显式安排清理工作,并明确地传播结果或失败。Ruby 的 ensure 会在离开受保护区域的正常展开过程中运行。清理代码中的 return 或新异常可能会覆盖原始结果。
Luau:完整程序
local function guarded()
local ok,err=pcall(function() error("bad") end)
print("cleanup")
return ok,err
end
local ok=guarded()
if not ok then print("handled") end
Ruby:完整程序
begin
begin
raise ArgumentError, "bad"
ensure
puts "cleanup"
end
rescue ArgumentError
puts "handled"
end挑战
简单定义 with_log(log),追加 open,yield 执行一次,且即使代码块引发异常也会追加 close。成功时返回代码块的结果并传播错误。solve 读取 ok 或 fail;使用一个返回 done 或引发 ArgumentError 的代码块。返回 done|open,close 或 error|open,close。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本(附带一个末尾换行符),并独立检查所需的公共 API。
你的代码放在 exercise.rb、session.rb 中。main.rb 包含提供的输入/输出代码,无法编辑。
亲手试试
require_relative 'exercise'
require_relative 'session'
def check(value)
raise 'Public API check failed' unless value
end
log = []
check(with_log(log) { 17 } == 17)
check(log == ["open", "close"])
begin
with_log(log) { raise KeyError, "probe" }
rescue KeyError
check(log == ["open", "close", "open", "close"])
end
check(log.length == 4)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器