Download Ruby Programming: Basic Types and Data Structures and more Schemes and Mind Maps Advanced Computer Programming in PDF only on Docsity!
Chapter 22
The Ruby Language
This chapter is a bottom-up look at the Ruby language. Most of what appears here is the
syntax and semantics of the language itself—we mostly ignore the built-in classes and
modules (these are covered in depth starting on page 402 ). However, Ruby sometimes
implements features in its libraries that in most languages would be part of the basic
syntax. We’ve included these methods here and have tried to flag them with “Library”
in the margin.
The contents of this chapter may look familiar—with good reason. We’ve covered just
about all of this in the earlier tutorial chapters. Consider this chapter to be a self-
contained reference to the core Ruby language.
Source Layout
Ruby programs are written in 7-bit ASCII, Kanji (using EUC or SJIS), or UTF-8. If
a code set other than 7-bit ASCII is used, the KCODE option must be set appropriately,
as shown on page 169.
Ruby is a line-oriented language. Ruby expressions and statements are terminated at
the end of a line unless the parser can determine that the statement is incomplete—for
example if the last token on a line is an operator or comma. A semicolon can be used to
separate multiple expressions on a line. You can also put a backslash at the end of a line
to continue it onto the next. Comments start with # and run to the end of the physical
line. Comments are ignored during syntax analysis.
a = 1 b = 2; c = 3 d = 4 + 5 + 6 + 7 # no '' needed e = 8 + 9 \
SOURCE LAYOUT 303
Physical lines between a line starting with =begin and a line starting with =end are
ignored by Ruby and may be used to comment out sections of code or to embed docu-
mentation.
Ruby reads its program input in a single pass, so you can pipe programs to the Ruby
interpreter’s standard input stream.
echo 'puts "Hello"' | ruby
If Ruby comes across a line anywhere in the source containing just “_ END _”, with
no leading or trailing whitespace, it treats that line as the end of the program—any
subsequent lines will not be treated as program code. However, these lines can be read
into the running program using the global IO object DATA, described on page 322.
BEGIN and END Blocks
Every Ruby source file can declare blocks of code to be run as the file is being loaded
(the BEGIN blocks) and after the program has finished executing (the END blocks).
BEGIN {
begin code }
END {
end code }
A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in
the order they are encountered. END blocks are executed in reverse order.
General Delimited Input
As well as the normal quoting mechanism, alternative forms of literal strings, arrays,
regular expressions, and shell commands are specified using a generalized delimited
syntax. All these literals start with a percent character, followed by a single character
that identifies the literal’s type. These characters are summarized in Table 22.1; the
actual literals are described in the corresponding sections later in this chapter.
Table 22.1. General delimited input
Type Meaning See Page
%q Single-quoted string 305
%Q, % Double-quoted string 305
%w, %W Array of strings 307
%r Regular expression pattern 309
%x Shell command 323
THE BASIC TYPES 305
?\cx (the control version of x is x & 0x9f). Meta characters (x | 0x80) can be gener-
ated using ?\M-x. The combination of meta and control is generated using and ?\M-\C-x.
You can get the integer value of a backslash character using the sequence ?\.
?a => 97 # ASCII character ?\n => 10 # code for a newline (0x0a) ?\C-a => 1 # control a = ?A & 0x9f = 0x ?\M-a => 225 # meta sets bit 7 ?\M-\C-a => 129 # meta and control a ?\C-? => 127 # delete character
A numeric literal with a decimal point and/or an exponent is turned into a Float object,
corresponding to the native architecture’s double data type. You must follow the dec-
imal point with a digit, as 1.e3 tries to invoke the method e3 in class Fixnum. As of
1.8 (^) Ruby 1.8you must also place at least one digit before the decimal point.
-0.1234e2 → -12.
1234e-2 → 12.
Strings
Ruby provides a number of mechanisms for creating literal strings. Each generates
objects of type String. The different mechanisms vary in terms of how a string is
delimited and how much substitution is done on the literal’s content.
Single-quoted string literals ('stuff ' and %q/stuff /) undergo the least substitution. Both
convert the sequence \ into a single backslash, and the form with single quotes con-
verts ' into a single quote. All other backslashes appear literally in the string.
'hello' → hello
'a backslash '\'' → a backslash ''
%q/simple string/ → simple string
%q(nesting (really) works) → nesting (really) works
%q no_blanks_here ; → no_blanks_here
Double-quoted strings ("stuff ", %Q/stuff /, and %/stuff /) undergo additional substitu-
tions, shown in Table 22.2 on the following page.
a = 123
"\123mile" → Smile
"Say "Hello"" → Say "Hello"
%Q!"I said 'nuts'," I said! → "I said 'nuts'," I said
%Q{Try #{a + 1}, not #{a - 1}} → Try 124, not 122
% → Try 124, not 122
"Try #{a + 1}, not #{a - 1}" → Try 124, not 122
%{ #{ a = 1; b = 2; a + b } } → 3
Strings can continue across multiple input lines, in which case they will contain newline
characters. It is also possible to use here documents to express long string literals.
Whenever Ruby parses the sequence <
THE BASIC TYPES 306
Table 22.2. Substitutions in double-quoted strings
\a Bell/alert (0x07) \nnn Octal nnn
\b Backspace (0x08) \xnn Hex nn
\e Escape (0x1b) \cx Control-x
\f Formfeed (0x0c) \C-x Control-x
\n Newline (0x0a) \M-x Meta-x
\r Return (0x0d) \M-\C-x Meta-control-x
\s Space (0x20) \x x
\t Tab (0x09) #{code} Value of code
\v Vertical tab (0x0b)
a string literal built from successive logical input lines. It stops building the string
when it finds a line that starts with identifier or quoted string. You can put a minus sign
immediately after the << characters, in which case the terminator can be indented from
the left margin. If a quoted string was used to specify the terminator, its quoting rules
will be applied to the here document; otherwise, double-quoting rules apply.
print <
THE BASIC TYPES 308
colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
There is no requirement for the keys and/or values in a particular hash to have the same
type.
Requirements for a Hash Key
Hash keys must respond to the message hash by returning a hash code, and the hash
code for a given key must not change. The keys used in hashes must also be comparable
using eql?. If eql? returns true for two keys, then those keys must also have the same
hash code. This means that certain classes (such as Array and Hash) can’t conveniently
be used as keys, because their hash values can change based on their contents.
If you keep an external reference to an object that is used as a key, and use that reference
to alter the object, thus changing its hash code, the hash lookup based on that key may
not work.
Because strings are the most frequently used keys, and because string contents are often
changed, Ruby treats string keys specially. If you use a String object as a hash key,
the hash will duplicate the string internally and will use that copy as its key. The copy
1.8 (^) will be frozen.Any changes made to the original string will not affect the hash.
If you write your own classes and use instances of them as hash keys, you need to
make sure that either (a) the hashes of the key objects don’t change once the objects
have been created or (b) you remember to call the Hash#rehash method to reindex the
hash whenever a key hash is changed.
Symbols
A Ruby symbol is an identifier corresponding to a string of characters, often a name.
You construct the symbol for a name by preceding the name with a colon, and you can
1.8 construct the symbol for an arbitrary string by preceding a string literal with a colon.
Substitution occurs in double-quoted strings. A particular name or string will always
generate the same symbol, regardless of how that name is used within the program.
:Object :my_variable :"Ruby rules" a = "cat"
:'catsup' → :catsup
:"#{a}sup" → :catsup
:'#{a}sup' → :"#{a}sup"
Other languages call this process interning, and call symbols atoms.
THE BASIC TYPES 309
Regular Expressions
Regular expression literals are objects of type Regexp. They are created explicitly by
calling the Regexp.new constructor or implicitly by using the literal forms, /pattern/
and %r{pattern}. The %r construct is a form of general delimited input (described on
pages 303 – 304 ).
/pattern/ /pattern/options %r{pattern} %r{pattern}options
Regexp.new( 'pattern' [ , options ] )
Regular Expression Options
A regular expression may include one or more options that modify the way the pattern
matches strings. If you’re using literals to create the Regexp object, then the options
are one or more characters placed immediately after the terminator. If you’re using
Regexp.new, the options are constants used as the second parameter of the constructor.
i Case Insensitive. The pattern match will ignore the case of letters in the pattern and
1.8 (^) string. Setting $=to make matches case insensitive is now deprecated.
o Substitute Once. Any #... substitutions in a particular regular expression literal
will be performed just once, the first time it is evaluated. Otherwise, the substitu-
tions will be performed every time the literal generates a Regexp object.
m Multiline Mode. Normally, “.” matches any character except a newline. With the
/m option, “.” matches any character.
x Extended Mode. Complex regular expressions can be difficult to read. The x option
allows you to insert spaces, newlines, and comments in the pattern to make it more
readable.
Another set of options allows you to set the language encoding of the regular expres-
sion. If none of these options is specified, the interpreter’s default encoding (set using
-K or $KCODE) is used.
n: no encoding (ASCII) e: EUC
s: SJIS u: UTF-
Regular Expression Patterns
regular characters
All characters except ., |, (, ), [, , ^, {, +, $, *, and? match themselves.
To match one of these characters, precede it with a backslash.
^ Matches the beginning of a line.
$ Matches the end of a line.
\A Matches the beginning of the string.
THE BASIC TYPES 311
(...) Parentheses are used to group regular expressions. For example, the
pattern /abc+/ matches a string containing an a, a b, and one or more
c’s. /(abc)+/ matches one or more sequences of abc. Parentheses are
also used to collect the results of pattern matching. For each opening
parenthesis, Ruby stores the result of the partial match between it and
the corresponding closing parenthesis as successive groups. Within the
same pattern, \1 refers to the match of the first group, \2 the second
group, and so on. Outside the pattern, the special variables $1, $2, and
so on, serve the same purpose.
1.8 (^) The anchor \Gworks with the repeating match methods String#gsub, String#gsub!,
String#index, and String#scan. In a repetitive match, it represents the position in
the string where the last match in the iteration ended. \G initially points to the start of
the string (or to the character referenced by the second parameter of String#index).
"a01b23c45 d56".scan(/[a-z]\d+/) → ["a01", "b23", "c45", "d56"]
"a01b23c45 d56".scan(/\G[a-z]\d+/) → ["a01", "b23", "c45"]
"a01b23c45 d56".scan(/\A[a-z]\d+/) → ["a01"]
Substitutions
#{...} Performs an expression substitution, as with strings. By default, the
substitution is performed each time a regular expression literal is eval-
uated. With the /o option, it is performed just the first time.
\0, \1, \2, ... \9, &, `, ', +
Substitutes the value matched by the nth grouped subexpression, or by
the entire match, pre- or postmatch, or the highest group.
Regular Expression Extensions
In common with Perl and Python, Ruby regular expressions offer some extensions over
traditional Unix regular expressions. All the extensions are entered between the char-
acters (? and ). The parentheses that bracket these extensions are groups, but they do
not generate back references: they do not set the values of \1 and $1 etc.
(?# comment )
Inserts a comment into the pattern. The content is ignored during pat-
tern matching.
(?: re ) Makes re into a group without generating backreferences. This is often
useful when you need to group a set of constructs but don’t want the
group to set the value of $1 or whatever. In the example that follows,
both patterns match a date with either colons or spaces between the
month, day, and year. The first form stores the separator character in $
and $4, but the second pattern doesn’t store the separator in an external
variable.
THE BASIC TYPES 312
date = "12/25/01" date =~ %r{(\d+)(/|:)(\d+)(/|:)(\d+)}
[$1,$2,$3,$4,$5] → ["12", "/", "25", "/", "01"]
date =~ %r{(\d+)(?:/|:)(\d+)(?:/|:)(\d+)}
[$1,$2,$3] → ["12", "25", "01"]
(?= re ) Matches re at this point, but does not consume it (also known charm-
ingly as zero-width positive lookahead). This lets you look forward for
the context of a match without affecting $&. In this example, the scan
method matches words followed by a comma, but the commas are not
included in the result.
str = "red, white, and blue"
str.scan(/[a-z]+(?=,)/) → ["red", "white"]
(?! re ) Matches if re does not match at this point. Does not consume the match
(zero-width negative lookahead). For example, /hot(?!dog)(\w+)/
matches any word that contains the letters hot that aren’t followed by
dog, returning the end of the word in $1.
(?> re ) Nests an independent regular expression within the first regular expres-
sion.anchored at the current match position. If it consumes characters,
these will no longer be available to the higher-level regular expression.
This construct therefore inhibits backtracking, which can be a perfor-
mance enhancement. For example, the pattern /a.b.a/ takes expo-
nential time when matched against a string containing an a followed
by a number of b’s, but with no trailing a. However, in some cases this
can be avoided by using a nested regular expression /a(?>.b).a/.
In this form, the nested expression consumes all the input string up to
the last possible b character. When the check for a trailing a then fails,
there is no need to backtrack, and the pattern match fails promptly.
(This pattern has different semantics than the original if the match
shouldn’t go up to the last b.)
require 'benchmark' include Benchmark str = "a" + ("b" (^) * 5000) bm(8) do |test| test.report("Normal:") { str =~ /^a.b.a/ } test.report("Nested:") { str =~ /^a(?>.b).a/ } end
produces:
user system total real Normal: 0.450000 0.000000 0.450000 ( 0.456447) Nested: 0.000000 0.000000 0.000000 ( 0.000412)
(?imx) Turns on the corresponding i, m, or x option. If used inside a group,
the effect is limited to that group.
NAMES 314
Table 22.3. Reserved words
FILE and def end in or self unless LINE begin defined? ensure module redo super until BEGIN break do false next rescue then when END case else for nil retry true while alias class elsif if not return undef yield
variables are listed starting on page 318. Finally, a global variable name can be formed
1.8 (^) using $- followed by a single letter or underscore.These latter variables typically mir-
ror the setting of the corresponding command-line option (see the table starting on
page 320 for details).
$params $PROGRAM $! $_ $-a $-K
Variable/Method Ambiguity
When Ruby sees a name such as a in an expression, it needs to determine if it is a local
variable reference or a call to a method with no parameters. To decide which is the case,
Ruby uses a heuristic. As Ruby parses a source file, it keeps track of symbols that have
been assigned to. It assumes that these symbols are variables. When it subsequently
comes across a symbol that could be a variable or a method call, it checks to see if
it has seen a prior assignment to that symbol. If so, it treats the symbol as a variable;
otherwise it treats it as a method call. As a somewhat pathological case of this, consider
the following code fragment, submitted by Clemens Hintze.
def a print "Function 'a' called\n" 99 end for i in 1.. if i == 2 print "a=", a, "\n" else a = 1 print "a=", a, "\n" end end
produces:
a= Function 'a' called a=
During the parse, Ruby sees the use of a in the first print statement and, as it hasn’t yet
seen any assignment to a, assumes that it is a method call. By the time it gets to the
second print statement, though, it has seen an assignment, and so treats a as a variable.
VARIABLES AND CONSTANTS 315
Note that the assignment does not have to be executed—Ruby just has to have seen it.
This program does not raise an error.
a = 1 if false; a
Variables and Constants
Ruby variables and constants hold references to objects. Variables themselves do not
have an intrinsic type. Instead, the type of a variable is defined solely by the messages
to which the object referenced by the variable responds.^2
A Ruby constant is also a reference to an object. Constants are created when they are
first assigned to (normally in a class or module definition). Ruby, unlike less flexible
languages, lets you alter the value of a constant, although this will generate a warning
message.
MY_CONST = 1
MY_CONST = 2 # generates a warning
produces:
prog.rb:2: warning: already initialized constant MY_CONST
Note that although constants should not be changed, you can alter the internal states of
the objects they reference.
MY_CONST = "Tim" MY_CONST[0] = "J" # alter string referenced by constant
MY_CONST → "Jim"
Assignment potentially aliases objects, giving the same object different names.
Scope of Constants and Variables
Constants defined within a class or module may be accessed unadorned anywhere
within the class or module. Outside the class or module, they may be accessed using the
scope operator, :: prefixed by an expression that returns the appropriate class or mod-
ule object. Constants defined outside any class or module may be accessed unadorned
or by using the scope operator :: with no prefix. Constants may not be defined in meth-
1.8 (^) ods. Constants may be addedto existing classes and modules from the outside by using
the class or module name and the scope operator before the constant name.
OUTER_CONST = 99
- When we say that a variable is not typed, we mean that any given variable can at different times hold references to objects of many different types.
VARIABLES AND CONSTANTS 317
This references the top-level object
def a.get_var @@var end
a.get_var → "top level variable"
Class variables are shared by children of the class in which they are first defined.
class Top @@A = 1 def dump puts values end def values "#{self.class.name}: A = #@@A" end end class MiddleOne < Top @@B = 2 def values super + ", B = #@@B" end end class MiddleTwo < Top @@B = 3 def values super + ", B = #@@B" end end class BottomOne < MiddleOne; end class BottomTwo < MiddleTwo; end Top.new.dump MiddleOne.new.dump MiddleTwo.new.dump BottomOne.new.dump BottomTwo.new.dump
produces:
Top: A = 1 MiddleOne: A = 1, B = 2 MiddleTwo: A = 1, B = 3 BottomOne: A = 1, B = 2 BottomTwo: A = 1, B = 3
Instance variables are available within instance methods throughout a class body. Ref-
erencing an uninitialized instance variable returns nil. Each instance of a class has a
unique set of instance variables. Instance variables are not available to class methods
(although classes (and modules) also may have instance variables—see page 371 ).
Local variables are unique in that their scopes are statically determined but their exis-
tence is established dynamically.
VARIABLES AND CONSTANTS 318
A local variable is created dynamically when it is first assigned a value during program
execution. However, the scope of a local variable is statically determined to be the
immediately enclosing block, method definition, class definition, module definition, or
top-level program. Referencing a local variable that is in scope but that has not yet
been created generates a NameError exception. Local variables with the same name
are different variables if they appear in disjoint scopes.
Method parameters are considered to be variables local to that method.
Block parameters are assigned values when the block is invoked.
a = [ 1, 2, 3 ] a.each {|i| puts i } # i local to block a.each {|$i| puts $i } # assigns to global $i a.each {|@i| puts @i } # assigns to instance variable @i a.each {|I| puts I } # generates warning assigning to constant a.each {|b.meth| } # invokes meth= in object b sum = 0 var = nil a.each {|var| sum += var } # uses sum and var from enclosing scope
If a local variable (including a block parameter) is first assigned in a block, it is local to
the block. If instead a variable of the same name is already established at the time the
block executes, the block will inherit that variable.
A block takes on the set of local variables in existence at the time that it is created.
This forms part of its binding. Note that although the binding of the variables is fixed
at this point, the block will have access to the current values of these variables when it
executes. The binding preserves these variables even if the original enclosing scope is
destroyed.
The bodies of while, until, and for loops are part of the scope that contains them;
previously existing locals can be used in the loop, and any new locals created will be
available outside the bodies afterward.
Predefined Variables
The following variables are predefined in the Ruby interpreter. In these descriptions,
the notation [r/o] indicates that the variables are read-only; an error will be raised if a
program attempts to modify a read-only variable. After all, you probably don’t want to
change the meaning of true halfway through your program (except perhaps if you’re
a politician). Entries marked [thread] are thread local.
Many global variables look something like Snoopy swearing: $_, $!, $&, and so on.
This is for “historical” reasons, as most of these variable names come from Perl. If
you find memorizing all this punctuation difficult, you may want to have a look at the
library file called English, documented on page 650 , which gives the commonly used
global variables more descriptive names.
VARIABLES AND CONSTANTS 320
$< Object An object that provides access to the concatenation of the contents of all the files given as command-line arguments or $stdin (in the case where there are no arguments). $< supports methods similar to a File object: binmode, close, closed?, each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno, lineno=, path, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip, tell, to_a, to_i, to_io, to_s, along with the methods in Enumerable. The method file returns a File object for the file currently being read. This may change as $< reads through the files on the command line. [r/o]
$> IO The destination of output for Kernel#print and Kernel#printf. The default value is $stdout. $_ String The last line read by Kernel#gets or Kernel#readline. Many string- related functions in the Kernel module operate on $_ by default. The vari- able is local to the current scope. [thread]
1.8 $defout IO Synonym for $>. Obsolete: use $stdout.
1.8 (^) $deferr IO Synonym for STDERR.Obsolete: use $stderr.
$-F String Synonym for $;.
$stderr IO The current standard error output.
$stdin IO The current standard input.
1.8 (^) $stdout IO The current standard output. Assignment to $stdoutis deprecated: use
$stdout.reopen instead.
Execution Environment Variables
$0 String The name of the top-level Ruby program being executed. Typically this will be the program’s filename. On some operating systems, assigning to this variable will change the name of the process reported (for example) by the ps(1) command. $* Array An array of strings containing the command-line options from the invoca- tion of the program. Options used by the Ruby interpreter will have been removed. [r/o]
$" Array An array containing the filenames of modules loaded by require. [r/o]
$$ Fixnum The process number of the program being executed. [r/o]
$? Process::Status The exit status of the last child process to terminate. [r/o, thread]
$: Array An array of strings, where each string specifies a directory to be searched for Ruby scripts and binary extensions used by the load and require methods. The initial value is the value of the arguments passed via the -I command- line option, followed by an installation-defined standard library location, fol- lowed by the current directory (“.”). This variable may be set from within a program to alter the default search path; typically, programs use $: << dir to append dir to the path. [r/o] $-a Object True if the -a option is specified on the command line. [r/o]
VARIABLES AND CONSTANTS 321
$-d Object Synonym for $DEBUG.
$DEBUG Object Set to true if the -d command-line option is specified.
FILE String The name of the current source file. [r/o]
$F Array The array that receives the split input line if the -a command-line option is used. $FILENAME String The name of the current input file. Equivalent to $<.filename. [r/o]
$-i String If in-place edit mode is enabled (perhaps using the -i command-line option), $-i holds the extension used when creating the backup file. If you set a value into $-i, enables in-place edit mode. See page 168. $-I Array Synonym for $:. [r/o]
$-K String Sets the multibyte coding system for strings and regular expressions. Equiv- alent to the -K command-line option. See page 169.
$-l Object Set to true if the -l option (which enables line-end processing) is present on the command line. See page 169. [r/o] LINE String The current line number in the source file. [r/o]
$LOAD_PATH Array A synonym for $:. [r/o]
$-p Object Set to true if the -p option (which puts an implicit while gets... end loop around your program) is present on the command line. See page 169. [r/o]
$SAFE Fixnum The current safe level (see page 380 ). This variable’s value may never be reduced by assignment. [thread] $VERBOSE Object Set to true if the -v, --version, -W, or -w option is specified on the com- 1.8 (^) mand line. Set to falseif no option, or -W1 is given. Set to nil if -W
was specified. Setting this option to true causes the interpreter and some library routines to report additional information. Setting to nil suppresses all warnings (including the output of Kernel.warn).
$-v Object Synonym for $VERBOSE.
$-w Object Synonym for $VERBOSE.
Standard Objects
ARGF Object A synonym for $<.
ARGV Array A synonym for $*.
ENV Object A hash-like object containing the program’s environment variables. An instance of class Object, ENV implements the full set of Hash methods. Used to query and set the value of an environment variable, as in ENV["PATH"] and ENV["term"]="ansi". false FalseClass Singleton instance of class FalseClass. [r/o]
nil NilClass The singleton instance of class NilClass. The value of uninitialized instance and global variables. [r/o]