O'Reilly logo

The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

BEGIN and END

BEGIN and ENDare reserved words in Ruby that declare code to be executed at the very beginning and very end of a Ruby program. (Note that BEGIN and END in capital letters are completely different from begin and end in lowercase.) If there is more than one BEGIN statement in a program, they are executed in the order in which the interpreter encounters them. If there is more than one END statement, they are executed in the reverse of the order in which they are encountered—that is, the first one is executed last. These statements are not commonly used in Ruby. They are inherited from Perl, which in turn inherited them from the awk text-processing language.

BEGIN and END must be followed by an open curly brace, any amount of Ruby code, and a close curly brace. The curly braces are required; do and end are not allowed here. For example:

BEGIN {
  # Global initialization code goes here
}

END {
  # Global shutdown code goes here
}

The BEGIN and END statements are different from each other in subtle ways. BEGIN statements are executed before anything else, including any surrounding code. This means that they define a local variable scope that is completely separate from the surrounding code. It only really makes sense to put BEGIN statements in top-level code; a BEGIN within a conditional or loop will be executed without regard for the conditions that surround it. Consider this code:

if (false) BEGIN { puts "if"; # This will be printed a = 4; # This variable only defined here } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required