Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 134 ยท Getting Started

Predefined Variables, Global Variables and BEGIN/END Blocks

Learn Ruby's predefined variables and constants - $0, $PROGRAM_NAME, ARGV, ENV, $stdout, $stderr, $~, $1, $!, $/ - plus your own globals, their pitfalls, and BEGIN, END and at_exit blocks.

Ruby comes with a set of variables that exist before your program starts. Some tell you about the program itself (its file name, its arguments, the Ruby version). Some are the standard input and output streams. Some are filled in automatically by the language: after a successful regular-expression match, $1 holds the first captured group, and inside a rescue clause $! holds the exception being handled. Many of these have cryptic punctuation names, which is a heritage from Perl and shell scripting, and most have a readable alias.

This lesson is a guided tour: the program-information variables and constants, the stream variables, the special variables set by regex matches and errors, the separator variables, how your own global variables work and why to be careful with them, and finally BEGIN, END and at_exit, which run code before and after the main program. If you only know ordinary variables, this is the step that lets you read other people's scripts.

Program information

Four things are worth knowing about the running program: its name, its arguments, its environment, and the Ruby it runs on.

Ruby Who am I, and where am I running?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • $0 and $PROGRAM_NAME are two names for the name of the script that was started. __FILE__ is the name of the file that contains the current line. They are equal only in the file you ran directly, which is why if __FILE__ == $0 is the standard guard for "run this part only when the file is executed, not when it is required" (scripting and CLIs). You can assign to $0; tools like top then show the new name.
  • ARGV is an array of the command-line arguments as strings. In the browser runner it is empty.
  • ENV behaves like a hash of environment variables. Use ENV.fetch("NAME", default) when a variable may be missing, because ENV["NAME"] returns nil and is easy to forget to check.
  • RUBY_VERSION, RUBY_ENGINE, RUBY_PLATFORM and RUBY_PATCHLEVEL are constants describing the interpreter (how Ruby runs).
  • __method__ is the name of the current method (a symbol, or nil outside methods), __LINE__ the current line number, and __dir__ the directory of the current file.
  • $$ is the process id of the running program.

The standard streams

$stdout, $stderr and $stdin are variables that hold the streams, and puts, print, p, warn and gets use them. The constants STDOUT, STDERR and STDIN always refer to the original streams. Because the variables can be reassigned, you can capture or redirect output without touching the code that prints. This is how test libraries check what a method prints.

Ruby Capturing output by replacing $stdout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When you replace a stream, always put the original back, ideally in an ensure block, or all later output keeps going to the buffer. Notice the last call to gets returns nil: the fake input is used up. See input and output for the everyday use of these streams.

Variables set by matches and errors

Some variables change by themselves. After a successful =~ match, $~ holds the MatchData and $1, $2 ... hold the captured groups. After a failed match all of them become nil. $` and $' hold the text before and after the match. Inside a rescue clause, $! is the current exception and $@ its backtrace; outside, $! is nil again.

Ruby $~, $1 and $!

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

These two groups are frame-local and thread-local: each method has its own $~, so a match inside a helper method does not change the caller's $1. They still make code hard to read, so modern Ruby style prefers explicit values: match = text.match(/.../) and match[1], or named captures, and rescue => error instead of $!. Read them when you see them; do not reach for them in new code (regex, exceptions).

Separators and the "last line" variable

A few variables control how Ruby splits and joins text. Their behavior is legacy, and some are deprecated, so treat the table as a reading aid:

Variable Meaning Default
$/ input record separator (what gets splits on) "\n"
$\ output record separator added by print nil
$, separator used by join and print when none is given (deprecated) nil
$; default separator for String#split (deprecated) nil
$_ the last line read by gets nil until a gets

Assigning a non-nil value to $, or $; is deprecated (Ruby warns when warnings are enabled), and the effect is global, so a library that sets it breaks every join in the program. Pass the separator explicitly instead: array.join(", ").

Your own global variables

Any name starting with $ is a global variable. It needs no declaration, can be read anywhere and, if never assigned, quietly evaluates to nil. That last point is the source of most bugs: a typo creates a new variable instead of an error.

Ruby Globals: convenient and dangerous

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output is 3, "global-variable", nil, nil, true, 13 and then counter is now 99. defined? tells you whether a global was ever assigned, global_variables lists them all, and trace_var runs a block each time one changes, which is a handy way to find who changes it.

Why avoid your own globals? Any code anywhere can change them, so you cannot reason about a function without reading the whole program; tests share them and leak state into each other; and there is no namespace, so two libraries can collide on $config. Better homes for shared state:

  • a constant for values that never change (DEFAULT_PORT = 8080),
  • a module or class with accessor methods (Config.port),
  • an argument passed to the methods that need it.

Use globals for what Ruby itself defines, such as $stdout.

BEGIN, END and at_exit

Ruby inherited two special blocks from awk and Perl. A BEGIN { ... } block runs as soon as the file is parsed, before any other code in the file, no matter where it appears. An END { ... } block runs when the program ends. at_exit { ... } does the same job as END but is an ordinary method call: it registers the block when that line is executed, and registered blocks run in reverse order, last registered first.

Ruby The order of BEGIN, END and at_exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The output order is: BEGIN block runs first, main starts, main ends, END inside a loop registers once, at_exit 2, at_exit 1, END block. Follow the exit handlers backwards: they were registered as END block, then at_exit 1, then at_exit 2, then the loop's END, and they run in the opposite order. An END block registers only once, even inside a loop, while at_exit registers every time it is executed. BEGIN is allowed only at the top level of a file.

In real programs you will see at_exit for flushing logs, removing temporary files and printing a summary; BEGIN and END appear almost only in one-line ruby -n or ruby -p scripts. Keep exit handlers short, and remember that they also run after an uncaught exception or exit (scripting and CLIs, hooks).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When is FILE == $0 true?

    $0 is the script that was started. FILE is the file holding the current line. They differ in files that another file requires, so the comparison guards code that should run only as a program.
  2. 2. What does an unassigned global variable such as $never_set return?

    Unlike local variables, an unset global (or instance variable) quietly evaluates to nil. A typo therefore silently creates a new variable.
  3. 3. Which happens when you assign $stdout = StringIO.new?

    puts and print write to whatever $stdout currently holds. The constant STDOUT still points to the original stream, so you can restore it with $stdout = STDOUT.
  4. 4. A program registers at_exit { puts 'A' } and then at_exit { puts 'B' }. What prints at exit?

    Exit handlers run in reverse order of registration, like a stack, so the last one registered runs first.
  5. 5. After "abc" =~ /(b)/ succeeds, what is $1?

    $1 holds the text matched by the first capture group. After a failed match it is nil again.

Summary

  • $0 / $PROGRAM_NAME, __FILE__, ARGV, ENV and the RUBY_* constants describe the running program; if __FILE__ == $0 runs code only when the file is started directly.
  • $stdout, $stderr and $stdin hold the streams that puts, warn and gets use. Replace them to capture or redirect output, and restore the originals.
  • $~, $1..$9, $` and $' are set by regex matches; $! and $@ by rescue. Prefer match[1] and rescue => error in new code.
  • $/, $\, $,, $; and $_ are legacy; avoid setting $, and $;.
  • Your own $globals need no declaration, return nil when unset and can be changed from anywhere; prefer constants, modules and arguments.
  • BEGIN runs first; END and at_exit run at exit, in reverse order of registration.

Next: Basic Types