×

ruby · level 2 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

runs every time, error or no error.

Some jobs must happen whatever goes wrong, like putting the lid back on or saving a log. Lines under ensure run every time: after the begin lines finish, after a rescue, and even when the error is not caught at all. An else part runs only when nothing went wrong.

Inside a def, or a do … end block, you can leave out begin. The whole method or block is watched, and rescue, else and ensure go straight before its end.

def share(sweets, friends)
  puts "#{sweets / friends} each"
rescue ZeroDivisionError
  puts "No friends to share with"
else
  puts "Shared fairly"
ensure
  puts "Lid back on the jar"
end
[3, 0].each { |friends| share(12, friends) }

The order is always rescue, then else, then ensure.