BUY THIS BOOK
Add to Cart

Print Book $24.95


Add to Cart

PDF $17.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £17.50

What is this?

Looking to Reprint or License this content?


Ruby in a Nutshell
Ruby in a Nutshell

By Yukihiro Matsumoto
Translated by David L.燫eynolds, Jr.
Book Price: $24.95 USD
£17.50 GBP
PDF Price: $17.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
Ruby has been readily adopted by programmers in Japan and has had much documentation written for it in Japanese. As programmers outside of Japan learn about the benefits of Ruby, there is a growing need for documentation in English. The first book I wrote for O'Reilly, Ruby Pocket Reference, was in Japanese. Since then Ruby has changed significantly. To meet the needs of non-Japanese programmers, we translated, updated, and expanded Ruby Pocket Reference into Ruby in a Nutshell.
Ruby is an object-oriented programming language that makes programming both enjoyable and fast. With the easy-to-use interpreter, familiar syntax, complete object-oriented functionality, and powerful class libraries, Ruby has become a language that can be applied to a broad range of fields from text processing and CGI scripts to professional, large-scale programs.
While Ruby is easy to learn, there are many details that you can't be expected to remember. This book presents those details in a clean and concise format. It is a reference to keep next to your desktop or laptop, designed to make Ruby even easier to use.
For those of you who are new to Ruby, there are several online tutorials available to get you started: Ruby's home page (http://www.ruby-lang.org) is a good starting pointing as it offers Ruby tutorials and the Ruby Language FAQ.
Ruby is a genuine object-oriented scripting language designed from the ground up to support the OOP model.
Most modern languages incorporate aspects of object-oriented programming. Because Ruby was designed from the beginning to support OOP, most programmers feel it is elegant, easy to use, and a pleasure to program. Everything in Ruby is an object; there's no exception.
While Ruby is object-oriented, you can also use Ruby to do procedural programming. But as you do, Ruby is secretly turning your nifty procedures into methods on a globally accessible object.
Throughout the development of the Ruby language, I've focused my energies on making programming faster and easier. To do so, I developed what I call the principle of least surprise
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ruby's Elegance
Ruby is a genuine object-oriented scripting language designed from the ground up to support the OOP model.
Most modern languages incorporate aspects of object-oriented programming. Because Ruby was designed from the beginning to support OOP, most programmers feel it is elegant, easy to use, and a pleasure to program. Everything in Ruby is an object; there's no exception.
While Ruby is object-oriented, you can also use Ruby to do procedural programming. But as you do, Ruby is secretly turning your nifty procedures into methods on a globally accessible object.
Throughout the development of the Ruby language, I've focused my energies on making programming faster and easier. To do so, I developed what I call the principle of least surprise. All features in Ruby, including object-oriented features, are designed to work as ordinary programmers (e.g., me) expect them to work. Here are some of those features:
Interpretive programming
No compilation is needed; you can edit and feed your program to the interpreter. The faster development cycle helps you enjoy the programming process.
Dynamic programming
Almost everything in Ruby is done at runtime. Types of variables and expressions are determined at runtime as are class and method definitions. You can even generate programs within programs and execute them.
Familiar syntax
If you've been programming in Java, Perl, Python, C/C++, or even Smalltalk, Ruby's syntax is easy to learn. The following simple factorial function illustrates how easily you can decipher its meaning:
def factorial(n)
  if n == 0
    return 1
  else
    return n * factorial(n-1)
  end
end
Iterators
The iterator feature for loop abstraction is built into the language, which means a block of code can be attached to a method call. The method can call back the block from within its execution. For example, Array has the each method to iterate over its contents. With this feature, you don't need to worry about the loop counter or boundary condition.
ary = [1,2,3,4,5]
ary.each do |i|
  puts 1*2
end  # prints 2,3,4,8,10 for each line
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Ruby in Action
Like Python or Perl, Ruby is a scripting language. Scripting languages offer some great advantages over other languages, such as C++ and Java. They allow programmers to show off a lot of programming concepts and principles in a relatively small amount of space. Ruby does this, while maintaining code readability.
# the "Hello World."
print "Hello World.\n"

# output file contents in reverse order
print File::readlines(path).reverse

# print lines that contains the word "Ruby".
while line = gets(  )
  if /Ruby/ =~ line
    print line
  end
end


# class and methods
class Animal
  def legs
    puts 4
  end
end

class Dog<Animal
  def bark
    puts "bow!"
  end
end

fred = Dog::new
fred.legs                # prints 4
fred.bark                # prints bow!

# exception handling
begin
  printf "size of %s is %d\n", path, File::size(path)
rescue
  printf "error! probably %s does not exist\n", path
end

# rename all files to lowercase names
ARGV.each {|path| File::rename(path, path.downcase)}

# network access
require 'socket'
print TCPSocket::open("localhost", "daytime").read

# Ruby/Tk
require 'tk'
TkButton.new(nil, 'text'=>'hello', 'command'=>'exit').pack
Tk.mainloop
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Language Basics
Ruby does what you'd expect it to do. It is highly consistent, and allows you to get down to work without having to worry about the language itself getting in your way.
Like most scripting language interpreters, Ruby is generally run from the command line. The interpreter can be invoked with the following options, which control the environment and behavior of the interpreter itself:
ruby [ options ] [鈥擼 [ programfile ] [ argument... ]
-a
Used with -n or -p to split each line. Split output is stored in $F.
-c
Checks syntax only, without executing program.
-C dir
Changes directory before executing (equivalent to -X).
-d
Enables debug mode (equivalent to -debug). Sets $DEBUG to true.
-e prog
Specifies prog as the program from the command line. Specify multiple -e options for multiline programs.
-F pat
Specifies pat as the default separator pattern ($;) used by split.
-h
Displays an overview of command-line options (equivalent to -help).
-i [ext]
Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file is deleted.
-I dir
Adds dir as the directory for loading libraries.
-K [kcode]
Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF-8; and a, A, n, or N for ASCII).
-l
Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.
-n
Places code within an input loop (as in while gets; ... end).
-0[octal]
Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.
-p
Places code within an input loop. Writes $_ for each iteration.
-r lib
Uses require to load lib as a library before executing.
-s
Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines the corresponding variable.
$xxx.-S
Searches for a program using the environment variable PATH.
-T [level]
Sets the level for tainting checks (1 if level not specified). Sets the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Command-Line Options
Like most scripting language interpreters, Ruby is generally run from the command line. The interpreter can be invoked with the following options, which control the environment and behavior of the interpreter itself:
ruby [ options ] [鈥擼 [ programfile ] [ argument... ]
-a
Used with -n or -p to split each line. Split output is stored in $F.
-c
Checks syntax only, without executing program.
-C dir
Changes directory before executing (equivalent to -X).
-d
Enables debug mode (equivalent to -debug). Sets $DEBUG to true.
-e prog
Specifies prog as the program from the command line. Specify multiple -e options for multiline programs.
-F pat
Specifies pat as the default separator pattern ($;) used by split.
-h
Displays an overview of command-line options (equivalent to -help).
-i [ext]
Overwrites the file contents with program output. The original file is saved with the extension ext. If ext isn't specified, the original file is deleted.
-I dir
Adds dir as the directory for loading libraries.
-K [kcode]
Specifies the multibyte character set code (e or E for EUC (extended Unix code); s or S for SJIS (Shift-JIS); u or U for UTF-8; and a, A, n, or N for ASCII).
-l
Enables automatic line-end processing. Chops a newline from input lines and appends a newline to output lines.
-n
Places code within an input loop (as in while gets; ... end).
-0[octal]
Sets default record separator ($/) as an octal. Defaults to \0 if octal not specified.
-p
Places code within an input loop. Writes $_ for each iteration.
-r lib
Uses require to load lib as a library before executing.
-s
Interprets any arguments between the program name and filename arguments fitting the pattern -xxx as a switch and defines the corresponding variable.
$xxx.-S
Searches for a program using the environment variable PATH.
-T [level]
Sets the level for tainting checks (1 if level not specified). Sets the $SAFE variable.
-v
Displays version and enables verbose mode (equivalent to --verbose).
-w
Enables verbose mode. If programfile
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Environment Variables
In addition to using arguments and options on the command line, the Ruby interpreter uses the following environment variables to control its behavior. The ENV object contains a list of current environment variables.
DLN_LIBRARY_PATH
Search path for dynamically loaded modules.
HOME
Directory moved to when no argument is passed to Dir::chdir. Also used by File::expand_path to expand "~".
LOGDIR
Directory moved to when no arguments are passed to Dir::chdir and environment variable HOME isn't set.
PATH
Search path for executing subprocesses and searching for Ruby programs with the -S option. Separate each path with a colon (semicolon in DOS and Windows).
RUBYLIB
Search path for libraries. Separate each path with a colon (semicolon in DOS and Windows).
RUBYLIB_PREFIX
Used to modify the RUBYLIB search path by replacing prefix of library path1 with path2 using the format path1;path2 or path1path2. For example, if RUBYLIB is:
 /usr/local/lib/ruby/site_ruby
and RUBYLIB_PREFIX is:
 /usr/local/lib/ruby;f:/ruby
Ruby searches f:/ruby/site_ruby. Works only with DOS, Windows, and OS/2 versions.
RUBYOPT
Command-line options passed to Ruby interpreter. Ignored in taint mode (where $SAFE is greater than 0).
RUBYPATH
With -S option, search path for Ruby programs. Takes precedence over PATH. Ignored in taint mode (where $SAFE is greater than 0).
RUBYSHELL
Specifies shell for spawned processes. If not set, SHELL or COMSPEC are checked.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Lexical Conventions
Ruby programs are composed of elements already familiar to most programmers: lines, whitespace, comments, identifiers, reserved words, literals, etc. Particularly for those programmers coming from other scripting languages such as Perl, Python or tcl, you'll find Ruby's conventions familiar, or at least straightforward enough not to cause much trouble.
We'll leave the thorny questions like "How much whitespace makes code more readable and how much is distracting?" for another day. If you haven't already caught onto this theme, the Ruby interpreter will do pretty much what you expect with respect to whitespace in your code.
Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled.
a + b
Interpreted as a+b (a is a local variable)
a +b
Interpreted as a(+b) (a, in this case, is a method call)
Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement.
Comments are lines of annotation within Ruby code that are ignored at runtime. Comments extend from # to the end of the line.
# This is a comment.
Ruby code can contain embedded documents too. Embedded documents extend from a line beginning with =begin to the next line beginning with =end. =begin and =end must come at the beginning of a line.
=begin
This is an embedded document.
=end
Identifiers are names of variables, constants, and methods. Ruby distinguishes between identifiers consisting of uppercase characters and those of lowercase characters. Identifier names may consist of alphanumeric characters and the underscore character ( _ ). You can distinguish a variable's type by the initial character of its identifier.
The following list shows the reserved words in Ruby:
BEGIN
do
next
then
END
else
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Literals
I've often wondered why we programmers are so enamored with literals. I'm waiting for the day when a language comes along and introduces "figuratives." In the interim, the rules Ruby uses for literals are simple and intuitive, as you'll see the following sections.
Strings and numbers are the bread and butter of literals. Ruby provides support for both integers and floating-point numbers, using classes Fixnum, Bignum, and Float.

Section 2.4.1.1: Integers

Integers are instances of class Fixnum or Bignum:
123                    # decimal
1_234                  # decimal with underline 
0377                   # octal
0xff                   # hexadecimal
0b1011                 # binary
?a                     # character code for 'a'
12345678901234567890   # Bignum:  an integer of infinite length

Section 2.4.1.2: Floating-point numbers

Floating-point numbers are instances of class Float:
123.4                    # floating point value
1.0e6                    # scientific notation
4E20                     # dot not required
4e+20                    # sign before exponential
A string is an array of bytes (octets) and an instance of class String:
"abc"
Double-quoted strings allow substitution and backslash notation.
'abc'
Single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'.

Section 2.4.2.1: String concatenation

Adjacent strings are concatenated at the same time Ruby parses the program.
"foo" "bar"           # means "foobar"

Section 2.4.2.2: Expression substitution

#$var and #@var are abbreviated forms of #{$var} and #{@var}. Embeds value of expression in #{...} into a string.

Section 2.4.2.3: Backslash notation

In double-quoted strings, regular expression literals, and command output, backslash notation can be represent unprintable characters, as shown in Table 2-1.
Table 2-1: Backslash notations
Sequence
Character represented
\n
Newline (0x0a)
\r
Carriage return (0x0d)
\f
Formfeed (0x0c)
\b
Backspace (0x08)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
There are five types of variables in Ruby: global, instance, class, locals and constants. As you might expect, global variables are accessible globally to the program, instance variables belong to an object, class variables to a class and constants are, well... constant. Ruby uses special characters to differentiate between the different kinds of variables. At a glance, you can tell what kind of variable is being used.
Global Variables
$foo
Global variables begin with $. Uninitialized global variables have the value nil (and produce warnings with the -w option). Some global variables have special behavior. See Section 3.1 in Chapter 3.
Instance Variables
@foo
Instance variables begin with @. Uninitialized instance variables have the value nil (and produce warnings with the -w option).
Class Variables
@@foo
Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined. Overriding class variables produce warnings with the -w option.
Local Variables
foo
Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}. The scope introduced by a block allows it to reference local variables outside the block, but scopes introduced by others don't. When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.
Constants
Foo
Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning, not an error. You may feel it contradicts the name "constant," but remember, this is listed under "variables."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operators
Ruby supports a rich set of operators, as you'd expect from a modern language. However, in keeping with Ruby's object-oriented nature, most operators are in fact method calls. This flexibility allows you to change the semantics of these operators wherever it might make sense.
Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument.
For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (+= -= etc.)
Here are the operators shown in order of precedence (highest to lowest):
::
[]
**
+(unary) -(unary) ! ~
* / %
+ -
<< >>
&
| ^
> >= < <=
<=> == === != =~ !~
&&
||
.. ...
?:
= (and abbreviated assignment operators such as +=, -=, etc.)
not
and or

Section 2.6.1.1: Nonmethod operators

The following operators aren't methods and, therefore, can't be redefined:
...
!
not
&&
and
||
or
::
=
+=, -=, (and other abbreviated assignment operators)
? : (ternary operator)

Section 2.6.1.2: Range operators

Range operators function differently depending on whether or not they appear in conditionals, if expressions, and while loops.
In conditionals, they return true from the point right operand is true until left operand is true:
expr1 .. expr2
Evaluates expr2 immediately after expr1 turns true.
expr1 ... expr2
Evaluates expr2 on the iteration after expr1 turns true.
In other contexts, they create a range object:
expr1 .. expr2
Includes both expressions (expr1 <= x <= expr2)
expr1 ... expr2
Doesn't include the last expression (expr1 <= x < expr2)

Section 2.6.1.3: Logical operators

If the value of the entire expression can be determined with the value of the left operand alone, the right operand isn't evaluated.
&& and
Returns true if both operands are true. If the left operand is false, returns the value of the left operand, otherwise returns the value of the right operand.
|| or
Returns true if either operand is
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Methods
Methods are the workhorses of Ruby; all of your carefully crafted algorithms live in methods on objects (and classes). In Ruby, "method" means both the named operation (e.g. "dump") and the code that a specific class provides to perform an operation.
Strictly speaking, Ruby has no functions, by which I mean code not associated with any object. (In C++, this is what you might call a "global-scope function".) All code in Ruby is a method of some object. But Ruby allows you the flexibility of having some methods appear and work just like functions in other languages, even though behind the scenes they're still just methods.
Normal Method Calls
obj.method([expr...[, *expr[, &expr]]]) obj.method [expr...[, *expr[, &expr]]] obj::method([expr...[, *expr[, &expr]]]) obj::method [expr...[, *expr[, &expr]]]
Calls a method. May take as arguments any number of expr followed by *expr and &expr. The last expression argument can be a hash declared directly without braces. *expr expands the array value of that expression and passes it to the method. &expr passes the Proc object value of that expression to the method as a block. If it isn't ambiguous, arguments need not be enclosed in parentheses. Either . or :: may be used to separate the object from its method, but it is customary in Ruby code to use :: as the separator for class methods.
method([expr...[, *expr[, &expr]]]) method [expr...[, *expr[, &expr]]]
Calls a method of self. This is the only form by which private methods may be called.
Within modules, module methods and private instance methods with the same name and definition are referred to by the general term module functions. This kind of method group can be called in either of the following ways:
Math.sin(1.0)
or:
include Math
sin(1.0)
You can append ! or ? to the name of a Ruby method. Traditionally, ! is appended to a method that requires more caution than the variant of the same name without !. A question mark ? is appended to a method that determines the state of a Boolean value, true or false.
Attempting to call a method without specifying either its arguments or parentheses in a context in which a local variable of the same name exists results in the method call being interpreted as a reference to the local variable, not a call to the method.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Control Structures
Ruby offers control structures that are pretty common to modern languages, but it also has a few unique ones.
if Statement
if conditional [then] code [elsif conditional [then] code]... [else code] end
Executes code if the conditional is true. True is interpreted as anything that isn't false or nil. If the conditional isn't true, code specified in the else clause is executed. An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon. The reserved word if can be used as a statement modifier.
code if conditional
Executes code if conditional is true.
unless Statement
unless conditional [then] code [else code] end
Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed. Like if, unless can be used as a statement modifier.
code unless conditional
Executes code unless conditional is true.
case Statement
case expression [when expression[, expression...] [then] code]... [else code] end
Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches. The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause. A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon.
while Statement
while conditional [do] code end
Executes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline,\, or a semicolon. The reserved word while can be used as statement modifier.
code while conditional
Executescode while conditional is true.
begin code end while conditional
If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.
until Statement
until conditional [do] code end
Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object-Oriented Programming
Phew, seems like a long time since I introduced Ruby as "the object-oriented scripting language," eh? But now you have everything you need to get the nitty-gritty details on how Ruby treats classes and objects. After you've mastered a few concepts and Ruby's syntax for dealing with objects, you may never want to go back to your old languages, so beware!
All Ruby data consists of objects that are instances of some class. Even a class itself is an object that is an instance of the Class class. As a general rule, new instances are created using the new method of a class, but there are some exceptions (such as the Fixnum class).
a = Array::new
s = String::new
o = Object::new
class Statement
class class_name [< superclass] code end
Defines a class. A class_name must be a constant. The defined class is assigned to that constant. If a class of the same name already exists, the class and superclass must match, or the superclass must not be specified, in order for the features of the new class definition to be added to the existing class. class statements introduce a new scope for local variables.
Class methods are defined with the def statement. The def statement adds a method to the innermost class or module definition surrounding the def statement. A def statement outside a class or module definition (at the top level) adds a method to the Object class itself, thus defining a method that can be referenced anywhere in the program.
When a method is called, Ruby searches for it in a number of places in the following order:
  1. Among the methods defined in that object (i.e., singleton methods).
  2. Among the methods defined by that object's class.
  3. Among the methods of the modules included by that class.
  4. Among the methods of the superclass.
  5. Among the methods of the modules included by that superclass.
  6. Repeats Steps 4 and 5 until the top-level object is reached.
Attribute definitions for a specific object can be made using the class definition construction. Uses for this form of class definition include the definition and a collection of singleton methods.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Security
Ruby is portable and can easily use code distributed across a network. This property gives you tremendous power and flexibility but introduces a commensurate burden: how do you use this capability without possibly causing damage?
Part of the answer lies in Ruby's security system, which allows you to "lock down" the Ruby environment when executing code that may be suspect. Ruby calls such data and code tainted. This feature introduces mechanisms that allow you to decide how and when potentially "dangerous" data or code can be used inside your Ruby scripts.
Ruby can execute programs with security checking turned on. The global variable $SAFE determines the level of the security check. The default safe level is 0, unless specified explicitly by the command-line option -T, or the Ruby script is run setuid or setgid.
$SAFE can be altered by assignment, but it isn't possible to lower the value of it:
$SAFE=1                # upgrade the safe level
$SAFE=4                #  upgrade the safe level even higher
$SAFE=0                # SecurityError!  you can't do it
$SAFE is thread local; in other words, the value of $SAFE in a thread may be changed without affecting the value in other threads. Using this feature, threads can be sandboxed for untrusted programs.
Thread::start {        # starting "sandbox" thread
  $SAFE = 4            # for this thread only
  ...                  # untrusted code
}
Level 0
Level 0 is the default safe level. No checks are performed on tainted data.
Any externally supplied string from IO, environment variables, and ARGV is automatically flagged as tainted.
The environment variable PATH is an exception. Its value is checked, and tainted only if any directory in it is writable by everybody.
Level 1
In this level, potentially dangerous operations using tainted data are forbidden. This is a suitable level for programs that handle untrusted input, such as CGI.
  • Environment variables RUBYLIB and RUBYOPT are ignored at startup.
  • Current directory (.) isn't included in $LOAD_PATH.
  • The command-line options
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Built-in Library Reference
We will now explore the core functionality that is built into the standard Ruby interpreter. You will find descriptions of more than 800 built-in methods in 42 classes and modules. Topics covered include predefined variables, predefined global constants, and built-in functions.
Ruby's predefined (built-in) variables affect the behavior of the entire program, so their use in libraries isn't recommended. The values in most predefined variables can be accessed by alternative means.
$!
The last exception object raised. The exception object can also be accessed using => in rescue clause.
$@
The stack backtrace for the last exception raised. The stack backtrace information can retrieved by Exception#backtrace method of the last exception.
$/
The input record separator (newline by default). gets, readline, etc., take their input record separator as optional argument.
$\
The output record separator (nil by default).
$,
The output separator between the arguments to print and Array#join (nil by default). You can specify separator explicitly to Array#join.
$;
The default separator for split (nil by default). You can specify separator explicitly for String#split.
$.
The number of the last line read from the current input file. Equivalent to ARGF.lineno.
$<
Synonym for ARGF.
$>
Synonym for $defout.
$0
The name of the current Ruby program being executed.
$$
The process.pid of the current Ruby program being executed.
$?
The exit status of the last process terminated.
$:
Synonym for $LOAD_PATH.
$DEBUG
True if the -d or --debug command-line option is specified.
$defout
The destination output for print and printf ($stdout by default).
$F
The variable that receives the output from split when -a is specified. This variable is set if the -a command-line option is specified along with the -p or -n option.
$FILENAME
The name of the file currently being read from ARGF. Equivalent to ARGF.filename.
$LOAD_PATH
An array holding the directories to be searched when loading files with the load and require methods.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Predefined Variables
Ruby's predefined (built-in) variables affect the behavior of the entire program, so their use in libraries isn't recommended. The values in most predefined variables can be accessed by alternative means.
$!
The last exception object raised. The exception object can also be accessed using => in rescue clause.
$@
The stack backtrace for the last exception raised. The stack backtrace information can retrieved by Exception#backtrace method of the last exception.
$/
The input record separator (newline by default). gets, readline, etc., take their input record separator as optional argument.
$\
The output record separator (nil by default).
$,
The output separator between the arguments to print and Array#join (nil by default). You can specify separator explicitly to Array#join.
$;
The default separator for split (nil by default). You can specify separator explicitly for String#split.
$.
The number of the last line read from the current input file. Equivalent to ARGF.lineno.
$<
Synonym for ARGF.
$>
Synonym for $defout.
$0
The name of the current Ruby program being executed.
$$
The process.pid of the current Ruby program being executed.
$?
The exit status of the last process terminated.
$:
Synonym for $LOAD_PATH.
$DEBUG
True if the -d or --debug command-line option is specified.
$defout
The destination output for print and printf ($stdout by default).
$F
The variable that receives the output from split when -a is specified. This variable is set if the -a command-line option is specified along with the -p or -n option.
$FILENAME
The name of the file currently being read from ARGF. Equivalent to ARGF.filename.
$LOAD_PATH
An array holding the directories to be searched when loading files with the load and require methods.
$SAFE
The security level. See Section 2.10.
0
No checks are performed on externally supplied (tainted) data. (default)
1
Potentially dangerous operations using tainted data are forbidden.
2
Potentially dangerous operations on processes and files are forbidden.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Predefined Global Constants
TRUE, FALSE, and NIL are backward-compatible. It's preferable to use true, false, and nil.
TRUE
Synonym for true.
FALSE
Synonym for false.
NIL
Synonym for nil.
ARGF
An object providing access to virtual concatenation of files passed as command-line arguments or standard input if there are no command-line arguments. A synonym for $<.
ARGV
An array containing the command-line arguments passed to the program. A synonym for $*.
DATA
An input stream for reading the lines of code following the __END__ directive. Not defined if __END__ isn't present in code.
ENV
A hash-like object containing the program's environment variables. ENV can be handled as a hash.
RUBY_PLATFORM
A string indicating the platform of the Ruby interpreter, e.g., i686-linux.
RUBY_RELEASE_DATE
A string indicating the release date of the Ruby interpreter, e.g., 2001-09-19.
RUBY_VERSION
A string indicating the version of the Ruby interpreter, e.g., 1.6.5.
STDERR
Standard error output stream. Default value of $stderr.
STDIN
Standard input stream. Default value of $stdin.
STDOUT
Standard output stream. Default value of $stdout.
TOPLEVEL_BINDING
A Binding object at Ruby's top level.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Built-in Functions
Since the Kernel module is included by Object class, its methods are available everywhere in the Ruby program. They can be called without a receiver (functional form), therefore, they are often called functions.
abort
Terminates program. If an exception is raised (i.e., $! isn't nil), its error message is displayed.
Array(obj)
Returns obj after converting it to an array using to_ary or to_a.
at_exit {...}
Registers a block for execution when the program exits. Similar to END statement (referenced in Section 2.8), but END statement registers the block only once.
autoload(classname, file)
Registers a class classname to be loaded from file the first time it's used. classname may be a string or a symbol.
autoload :Foo, "foolib.rb".
binding
Returns the current variable and method bindings. The Binding object that is returned may be passed to the eval method as its second argument.
block_given?
Returns true if the method was called with a block.
callcc {|c|...}
Passes a Continuation object c to the block and executes the block. callcc can be used for global exit or loop construct.
def foo(c)
  puts "in foo"           #
  c.call                  # jump out
  puts "out foo"          # this line never be executed
end
callcc{|c| foo(c)}        # prints "in foo"
caller([n])
Returns the current execution stack in an array of the strings in the form file:line. If n is specified, returns stack entries from nth level on down.
catch(tag) {...}
Catches a nonlocal exit by a throw called during the execution of its block.
def throwing(n)
  throw(:exit, n+2)
end

catch(:exit) {
  puts "before throwing"
  throwing(5)
  puts "after throwing"   # this line never be executed
} # returns 7
chomp([rs=$/])
Returns the value of variable $_ with the ending newline removed, assigning the result back to $_. The value of the newline string can be specified with rs.
$_ = "foo\n"
chomp                     # $_ => "foo"
$_ = "foo"
chomp                     # no chomp
chomp!([rs=$/])
Removes newline from $_, modifying the string in place.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Built-in Library
Ruby's built-in library provides you with a rich set of classes that form the foundation for your Ruby programs. There are classes for manipulating text (String), operating system services and abstractions (IO, File, Process, etc.), numbers (Integer, Fixnum, etc.), and so on.
Using these basic building blocks, you can build powerful Ruby programs. But wait, in the next chapter, I lay out the Standard Library, which extends Ruby's flexibility.
Ruby couldn't lay claim to being an "object-oriented scripting language" without providing fundamental tools for OOP. This basic support is provided through the Object class.
Object
Superclass of all classes
Object is the parent class of all other classes. When a method is defined at the top level, it becomes a private method of this class, making it executable by all classes as if it were a function in other languages.
Included Modules
Kernel
Private Instance Methods
initialize