ruby · level 2 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Which lines run? Guess the output.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
begin
Integer("lots")
puts "Baking"
rescue ArgumentError
puts "Bad amount"
else
puts "Cake ready"
ensure
puts "Washing up"
end
your turn
Your turn. Run a safe calculator.
Fill in two whole numbers to divide, then press run. Try 0 as the second number too, and watch ensure run both times.
fix it
The shop only closes when things go well. Fix it!
- Shop closed never shows. Where does Ruby jump when line 2 raises an error?
- Ruby skips the rest of the method and jumps to
rescue. Lines that must always run belong underensure. - Move the Shop closed line under a new
ensureline, right before the method'send.
nailed it
you tidy up, whatever happens. :D
ensureruns every time, error or not.elseruns only when nothing went wrong.- Inside a
defordoblock,rescueneeds nobegin.
new words in your collection
- ensure
This lesson isn’t saved. A free account remembers every lesson you finish.