Ensure and Cleanup
Lesson 24 of 48 in Coddy's Ruby for Rust Developers course.
Rust Drop-based guards clean up when values leave scope, including ordinary Result returns and panic unwinding when enabled. Ruby ensure runs when leaving a protected region during ordinary execution and exception unwinding. These are different ownership and cleanup models. Keep cleanup separate from results, and avoid a Ruby return in ensure that overrides an earlier outcome.
Rust: complete program
struct Cleanup;
impl Drop for Cleanup{fn drop(&mut self){println!("cleanup");}}
fn guarded()->Result<(),&'static str>{let _cleanup=Cleanup;Err("bad")}
fn main(){
if guarded().is_err(){println!("handled");}
}
Ruby: complete program
begin
begin
raise ArgumentError, "bad"
ensure
puts "cleanup"
end
rescue ArgumentError
puts "handled"
endChallenge
EasyDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Rust Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip4Mutation and Errors
Mutation and AliasesNil and Optional ValuesExceptions and ValidationEnsure and CleanupRecap: Safe Ratio2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler