Skip to Content
The Ruby Programming Language
book

The Ruby Programming Language

by David Flanagan, Yukihiro Matsumoto
January 2008
Beginner to intermediate
446 pages
14h 45m
English
O'Reilly Media, Inc.
Content preview from The Ruby Programming Language

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 } ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Metaprogramming Ruby 2

Metaprogramming Ruby 2

Paolo Perrotta

Publisher Resources

ISBN: 9780596516178Supplemental ContentErrata Page