Menu
CoddyTech

确保与清理

Coddy Ruby for C++ Developers 课程的第 24 课,共 48 课。

C++ 的 RAII 会在普通的栈展开过程中销毁作用域内的对象,因此资源包装器可以在外层 catch 执行前进行清理。Ruby 的 ensure 会在普通展开过程中离开受保护部分时执行清理。它不能直接替代 C++ 中所有权和析构函数的每一条规则。从 Ruby 的 ensure 返回可能会覆盖之前的结果或异常。

C++:完整程序

#include <iostream>
#include <stdexcept>
struct Cleanup {~Cleanup(){std::cout<<"cleanup\n";}};

int main() {
try{Cleanup cleanup;throw std::runtime_error("bad");}catch(const std::runtime_error&){std::cout<<"handled\n";}
}

Ruby:完整程序

begin
  begin
    raise ArgumentError, "bad"
  ensure
    puts "cleanup"
  end
rescue ArgumentError
  puts "handled"
end
challenge icon

挑战

简单

定义 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)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

Ruby for C++ Developers中的所有课

自己练习: Ruby 在线编译器