File Structure

There are only a few rules about how a file of Ruby code must be structured. These rules are related to the deployment of Ruby programs and are not directly relevant to the language itself.

First, if a Ruby program contains a “shebang” comment, to tell the (Unix-like) operating system how to execute it, that comment must appear on the first line.

Second, if a Ruby program contains a “coding” comment (as described in Specifying Program Encoding), that comment must appear on the first line or on the second line if the first line is a shebang.

Third, if a file contains a line that consists of the single token __END__ with no whitespace before or after, then the Ruby interpreter stops processing the file at that point. The remainder of the file may contain arbitrary data that the program can read using the IO stream object DATA. (See Chapter 10 and Input/Output for more about this global constant.)

Ruby programs are not required to fit in a single file. Many programs load additional Ruby code from external libraries, for example. Programs use require to load code from another file. require searches for specified modules of code against a search path, and prevents any given module from being loaded more than once. See Loading and Requiring Modules for details.

The following code illustrates each of these points of Ruby file structure:

#!/usr/bin/ruby -w          shebang comment
# -*- coding: utf-8 -*-     coding comment
require 'socket'            load networking library

  ...                       program code goes here ...

Get The Ruby Programming Language 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.