Menu
CoddyTech

Ensure and Cleanup

Lesson 24 of 48 in Coddy's Ruby for C++ Developers course.

C++ RAII destroys scoped objects during ordinary stack unwinding, so resource wrappers can clean up before an outer catch. Ruby ensure performs cleanup when leaving its protected section during ordinary unwinding. It is not a direct replacement for every C++ ownership and destructor rule. Returning from Ruby ensure can override an earlier result or exception.

C++: complete program

#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: complete program

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

Challenge

Easy

Define with_log(log) that appends open, yields once, and appends close even if the block raises. Return the block result on success and propagate errors. solve reads ok or fail; use a block returning done or raising ArgumentError. Return done|open,close or error|open,close.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, session.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for C++ Developers

Practice on your own: Online Ruby compiler