DEV Community

Discussion on: #GopherDiggingRuby: Intro to blocks in Ruby

Collapse
 
nevans profile image
nicholas a. evans

If you're using this pattern with resources which need to be cleaned up, don't forget to ensure! :)

def get_blender
  blender = take_blender_out_of_cabinet()
  blender.plug_in()

  yield blender
ensure
  if blender
    clean_up blender
    put_away blender
  end
end
Enter fullscreen mode Exit fullscreen mode

Without ensure, your cleanup can be bypassed with

  • raise exception anywhere later
  • throw tag anywhere down the stack
  • break exits the block it's in
  • return exits the method it's in

Using ensure get's you back to what you're used to with defer.

Collapse
 
andyhaskell profile image
Andy Haskell

Thanks for sharing that Ruby idiom, I had not heard about that keyword before!