Skip to content

Instantly share code, notes, and snippets.

@Roman2K
Created November 24, 2012 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Roman2K/4137772 to your computer and use it in GitHub Desktop.
Save Roman2K/4137772 to your computer and use it in GitHub Desktop.
Misplaced "ensures" in sample code from:
http://railsware.com/blog/2012/11/20/yield-gotcha-in-ruby-blocks/
Always be careful when adding "ensure" statements. Variables used within its
block may not have been assigned if an exception is raised within the "begin"
block. In fact, this mistake is often the result of not bothering with a "begin"
statement altogether
def ensured_with_file(name, &block)
puts "Open file"
f = File.open(name, "r")
yield f
ensure
#
# /!\ f may be nil if File.open raises
#
puts "Close file"
f.close
end
def ensured_with_file(name, &block)
puts "Open file"
f = File.open(name, "r")
begin
yield f
ensure
puts "Close file"
f.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment