Other Uses for Blocks

BEGIN and END are special constructs that are not commonly used, but they can help you make your scripts robust and well-behaved. Regardless of where it appears, a block attached to the keyword BEGIN executes before the rest of your script, and a block attached to END executes last:

#!/usr/bin/env ruby

BEGIN { puts "Starting..." }
END   { puts "Done." }
puts "Working..."

   # Output:  Starting...
   #          Working...
   #          Done.
					

END is particularly useful, because it can help a script clean up after itself. If you use use the ANSI module we wrote back on Day 11 and get careless, your programs might exit leaving the terminal window in a strange state, maybe even with flashing blue text on a pink background. Spare yourself that embarrassment. ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.