ensure 与清理
Coddy 面向 Lua 开发者的 Ruby 课程的第 24 课,共 48 课。
Lua 5.1 没有通用的 finally 语法。你可以在受保护的调用之后安排清理操作,然后传播失败或有意地处理它。Lua 5.4 为合适的值添加了待关闭变量,但这些示例不需要这个较新的特性。Ruby 的 ensure 集成在普通的异常展开过程中,会在外层 rescue 接收到失败之前运行。
Lua:完整程序
local ok = pcall(function() error("bad") end)
print("cleanup")
if not ok then print("handled") endRuby:完整程序
begin
begin
raise ArgumentError, "bad"
ensure
puts "cleanup"
end
rescue ArgumentError
puts "handled"
end挑战
简单定义 with_log(log),让它追加 open,执行一次代码块,并且即使代码块引发异常,也追加 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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Lua 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器