|
|||
Previous < |
Contents ^
|
Next >
|
KCODE
option must be
set appropriately, as shown on page 137.]
Ruby is a line-oriented language. Ruby expressions and statements are
terminated at the end of a line unless the statement is obviously
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 compilation.
a = 1 b = 2; c = 3 d = 4 + 5 + # no '\' needed 6 + 7 e = 8 + 9 \ + 10 # '\' needed |
{=begin documentation}
a line starting with =end are
ignored by the compiler and may be used for embedded documentation
(see Appendix A, which begins on page 511).
Ruby reads its program input in a single pass, so you can pipe
programs to the compiler's stdin
.
echo 'print "Hello\n"' | ruby |
__END__
'',
with no leading or trailing whitespace, it
treats that line as the end of the program---any subsequent lines will not be
compiled. However, these lines can be read into the running program
using the global IO
object DATA
, described
on page 217.
BEGIN
blocks) and after the program
has finished executing (the END
blocks).
BEGIN { begin code } END { end code } |
BEGIN
and END
blocks.
BEGIN
blocks are executed in the order they are encountered.
END
blocks are executed in reverse order.
General delimited input
|
(
'',
``[
'', ``{
'', or ``<
'', the literal consists of the
characters up to the matching closing delimiter, taking account of
nested delimiter pairs. For all other delimiters, the literal
comprises the characters up to the next occurrence of the delimiter
character.
%q/this is a string/ %q-string- %q(a (nested) string) |
%q{def fred(a) a.each { |i| puts i } end} |
Fixnum
or Bignum
.
Fixnum
objects
hold integers that fit within the native machine word minus 1 bit.
Whenever a Fixnum
exceeds this range, it is automatically converted
to a Bignum
object, whose range is effectively limited only
by available memory. If an operation with a Bignum
result
has a final value that will fit in a Fixnum
, the result will
be returned as a Fixnum
.
Integers are written using an optional leading sign, an optional base
indicator (0
for octal, 0x
for hex, or 0b
for binary), followed by a string of digits in the appropriate base.
Underscore characters are ignored in the digit string.
You can get the integer value corresponding to an ASCII
character by preceding that character with a question mark. Control
and meta combinations of characters can also be generated using
?\C-x, ?\M-x, and ?\M-\C-x.
The control version of ch
is ch&0x9f
, and the meta
version is ch | 0x80
. You can get the integer value of a backslash
character using the sequence ?\\
.
123456 # Fixnum 123_456 # Fixnum (underscore ignored) -543 # Negative Fixnum 123_456_789_123_345_789 # Bignum 0xaabb # Hexadecimal 0377 # Octal -0b1010 # Binary (negated) 0b001_001 # Binary ?a # character code ?A # upper case ?\C-a # control a = A - 0x40 ?\C-A # case ignored for control chars ?\M-a # meta sets bit 7 ?\M-\C-a # meta and control a |
Float
object, corresponding to the native
architecture's double
data type. You must
follow the decimal point with a digit, as
1.e3
tries to invoke the method e3
in class Fixnum
.
12.34
|
» |
12.34
|
-.1234e2
|
» |
-12.34
|
1234e-2
|
» |
12.34
|
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
'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
|
Substitutions in double-quoted
strings
|
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 #{a + 1}, not #{a - 1}>
|
» |
Try 124, not 122
|
"Try #{a + 1}, not #{a - 1}"
|
» |
Try 124, not 122
|
a = 123 print <<HERE Double quoted \ here document. Sum = #{a + 1} HERE print <<-'THERE' This is single quoted. The above used #{a + 1} THERE |
Double quoted here document. Sum = 124 This is single quoted. The above used #{a + 1} |
String
object.
'Con' "cat" 'en' "ate"
|
» |
"Concatenate"
|
jcode
library supports a set of operations of
strings written with EUC, SJIS, or UTF-8
encoding.
The underlying string, however, is still accessed as a
series of bytes.] and each byte may contain any of the 256 8-bit
values, including null and newline.
The substitution mechanisms in
Table 18.2 on page 203 allow nonprinting characters to be
inserted conveniently and portably.
Every time a string literal is used in an assignment or as a
parameter, a new String
object is created.
for i in 1..3 print 'hello'.id, " " end |
537763324 537763034 537763004 |
String
starts on page 363.
..
expr and expr
...
expr
construct Range
objects.
The two-dot form is an inclusive range;
the one with three dots is a range that excludes its last element.
See the description of class Range
on page 359 for
details. Also see the description of conditional expressions
on page 222 for other uses of ranges.
Array
are created by placing a comma-separated
series of object references between square brackets. A trailing comma
is ignored.
arr = [ fred, 10, 3.14, "This is a string", barney("pebbles"), ] |
%w
,
which extracts space-separated tokens into successive
elements of the array. A space can be escaped with a backslash.
This is a form of general delimited input,
described on pages 200--201.
arr = %w( fred wilma barney betty great\ gazoo )
|
||
arr
|
» |
["fred", "wilma", "barney", "betty", "great gazoo"]
|
Hash
is created by placing a list of key/value
pairs between braces, with either a comma or the sequence =>
between the key and the value. A trailing comma is ignored.
colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f } |
hash
with a hash value, and the hash value for a
given key must not change.
This means that certain classes (such as
Array
and Hash
, as of this writing) 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 and change its hash value,
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. Any changes
subsequently 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.
:Object :myVariable |
Regexp
. They can
be created by explicitly calling the
Regexp.new
constructor, or
by using the literal forms, /pattern/ and
%r{
pattern
}
. The %r
construct is
a form of general delimited input (described
on pages 200--201).
/pattern/ /pattern/options %r{pattern} %r{pattern}options Regexp.new( 'pattern' [, options ] ) |
Regexp
object, then the options comprise 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 string. Matches are also
case-insensitive if the global variable $= is set. |
o
|
Substitute Once. Any #{...} substitutions
in
a particular regular expression literal will be performed just once,
the first time it is evaluated. Otherwise, the substitutions
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. |
^
$
\A
\z
\Z
\b
, \B
[
characters
]
|, (, ), [, ^, $, *,
and ?
,
which have special meanings elsewhere in patterns, lose their
special significance between brackets. The sequences
\
nnn, \x
nn, \c
x, \C-
x, \M-
x, and \M-\C-
x
have the meanings shown in Table 18.2 on page 203. The
sequences \d
, \D
, \s
, \S
, \w
, and \W
are abbreviations for groups of characters, as
shown in Table 5.1 on page 59. The sequence c1-c2
represents all the characters between c1 and c2, inclusive.
Literal ]
or -
characters must appear immediately after
the opening bracket. An uparrow (^) immediately following the
opening bracket negates the sense of the match---the pattern matches
any character that isn't in the character class.
\d
, \s
, \w
.
(period)
/m
option, it matches newline, too).
*
+
{m,n}
?
*
, +
, and {m,n}
modifiers are greedy by
default. Append a question mark to make them minimal.
|
re2
|
has a low
precedence.
(...)
/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.
#{...}
/o
option, it is performed just the first
time.
\0, \1, \2, ... \9, \&, \`, \', \+
(?
and )
. The parentheses
that bracket these extensions are groups, but they do not generate
backreferences: they do not set the values of \1
and $1
etc.
(?# comment)
(?:re)
$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 $2
and $4
, while the second
pattern doesn't store the separator in an external variable.
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)
$&
. 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)
/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)
/a.*b.*a/
takes exponential time when matched
against a string containing an ``a'' followed by a number of ``b''s,
but with no trailing ``a.'' However, this can be avoided by using a
nested regular expression /a(?>.*b).*a/
. In this form, the
nested expression consumes all the 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.
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 |
user system total real Normal: 4.170000 0.000000 4.170000 ( 4.150970) Nested: 0.000000 0.000000 0.000000 ( 0.001529) |
(?imx)
(?-imx)
(?imx:re)
(?-imx:re)
Reserved words
|
fred anObject _x three_two_one |
@
'') followed by an
upper- or lowercase letter, optionally followed by name
characters.
@name @_ @Size |
@@
'')
followed by an upper- or lowercase letter, optionally followed by name
characters.
@@name @@_ @@Size |
module Math PI = 3.1415926 end class BigBlob |
$
'') followed by name characters. In addition,
there is a set of two-character variable names in which the second
character is a punctuation character. These predefined variables are
listed starting on page 213. Finally, a global variable name
can be formed using ``$-
'' followed by any single character.
$params $PROGRAM $! $_ $-a $-. |
def a print "Function 'a' called\n" 99 end for i in 1..2 if i == 2 print "a=", a, "\n" else a = 1 print "a=", a, "\n" end end |
a=1 Function 'a' called a=99 |
a = 1 if false; a |
MY_CONST = 1 MY_CONST = 2 # generates a warning |
prog.rb:2: warning: already initialized constant MY_CONST |
MY_CONST = "Tim"
|
||
MY_CONST[0] = "J" # alter string referenced by constant
|
||
MY_CONST
|
» |
"Jim"
|
::
'' prefixed by an
expression that returns the appropriate class or module 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 methods.
OUTER_CONST = 99
|
||
class Const
|
||
def getConst
|
||
CONST
|
||
end
|
||
CONST = OUTER_CONST + 1
|
||
end
|
||
Const.new.getConst
|
» |
100
|
Const::CONST
|
» |
100
|
::OUTER_CONST
|
» |
99
|
nil
.
Class variables are available throughout a class or module body. Class
variables must be initialized before use. A class variable is shared
among all instances of a class and is available within the class
itself.
class Song @@count = 0 def initialize @@count += 1 end def Song.getCount @@count end end |
Object
, and behave like global variables. Class variables defined
within singleton methods belong to the receiver if the receiver is a
class or a module; otherwise, they belong to the class of the receiver.
class Holder @@var = 99 def Holder.var=(val) @@var = val end end a = Holder.new def a.var @@var end |
Holder.var = 123
|
||
a.var
|
» |
123
|
nil
. Each instance of a class has a unique set of instance
variables. Instance variables are not available to class methods.
Local variables are unique in that their scopes are statically determined
but their existence is established dynamically.
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 |
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.
true
halfway through your program (except perhaps
if you're a politician). Entries marked {} 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 might want to have a look at the
library file called ``English,''
documented
on page 445, which gives the commonly used global variables
more descriptive names.
In the tables of variables and constants that follow, we show the
variable name, the type of the referenced object, and a description.
$! | Exception | The exception object passed to raise .
{} |
$@ | Array | The stack backtrace generated by the last
exception. See
Kernel#caller
on page 413 for details. {} |
$=
) are set to nil
after an
unsuccessful pattern match.
$& | String | The string matched by the last successful pattern match. This variable is local to the current scope. {} |
$+ | String | The contents of the highest-numbered group matched
in the last successful pattern match. Thus, in
"cat" =~/(c|a)(t|z)/ , $+ will be set to
``t''. This variable is local to the current
scope. {} |
$` | String | The string preceding the match in the last successful pattern match. This variable is local to the current scope. {} |
$' | String | The string following the match in the last successful pattern match. This variable is local to the current scope. {} |
$= | Object | If set to any value apart from nil or
false , all pattern matches will be case
insensitive, string comparisons will ignore case,
and string hash values will be case insensitive. |
$1 to $9 | String | The contents of successive groups matched in the
last successful pattern match. In
"cat" =~/(c|a)(t|z)/ , $1 will be set to
``a'' and $2 to ``t''. This variable is
local to the current scope. {} |
$~ | MatchData | An object that encapsulates the results of a
successful pattern match. The variables $& ,
$` , $' , and $1 to $9 are all
derived from $~ . Assigning to $~
changes the values of these derived
variables. This variable is local to the current
scope. {} |
$/ | String | The input record separator (newline by
default). This is the value that routines such as
Kernel#gets
use to determine record
boundaries. If set to nil , gets will read
the entire file. |
$-0 | String | Synonym for $/ . |
$\ | String | The string appended to the output of every call to methods such
as
Kernel#print
and
IO#write
. The
default value is nil . |
$, | String | The separator string output between the parameters to
methods such as
Kernel#print
and
Array#join
. Defaults to nil , which adds no text. |
$. | Fixnum | The number of the last line read from the current input file. |
$; | String | The default separator pattern used by
String#split
.
May be set from the command line using the
-F
flag. |
$< | 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= , 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. {} |
$> | 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 variable is local to the current
scope. {} |
$defout | IO | Synonym for $> . |
$-F | String | Synonym for $; . |
$stderr | IO | The current standard error output. |
$stdin | IO | The current standard input. |
$stdout | IO | The current standard output. |
$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 invocation of the program. Options used by the Ruby interpreter will have been removed. {} |
$" | Array | An array containing the filenames of modules
loaded by
require .
{} |
$$ | Fixnum | The process number of the program being executed. {} |
$? | Fixnum | The exit status of the last child process to terminate. {} |
$: | 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, followed 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. {} |
$-a | Object | True if the -a option is specified on the
command line. {} |
$-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. {} |
$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 . {} |
$-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 136. |
$-I | Array | Synonym for $: . {} |
$-K | String | Sets the multibyte coding system for strings and
regular expressions. Equivalent to the
-K
command-line option. See page
137. |
$-l | Object | Set to true if the -l option
(which enables line-end processing) is present on
the command line. See page
137. {} |
__LINE__ | String | The current line number in the source file. {} |
$LOAD_PATH | Array | A synonym for $: . {} |
$-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
137. {} |
$SAFE | Fixnum | The current safe level (see page 254). This variable's value may never be reduced by assignment. {} |
$VERBOSE | Object | Set to true if the -v ,
--version , or
-w option is
specified on the command line. Setting this option
to true causes the interpreter and some
library routines to report additional
information. |
$-v | Object | Synonym for $VERBOSE . |
$-w | Object | Synonym for $VERBOSE . |
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 . {} |
nil | NilClass | The singleton instance of class
NilClass . The value of uninitialized
instance and global variables. {} |
self | Object | The receiver (object) of the current method. {} |
true | TrueClass | Singleton instance of class TrueClass . {} |
DATA | IO | If the the main program file contains the directive
__END__ ,
then the constant DATA
will be initialized so that reading from it will return lines
following __END__ from the source file. |
FALSE | FalseClass | Synonym for false . |
NIL | NilClass | Synonym for nil . |
RUBY_PLATFORM | String | The identifier of the platform running this program. This string is in the same form as the platform identifier used by the GNU configure utility (which is not a coincidence). |
RUBY_RELEASE_DATE | String | The date of this release. |
RUBY_VERSION | String | The version number of the interpreter. |
STDERR | IO | The actual standard error stream for the program. The
initial value of $stderr . |
STDIN | IO | The actual standard input stream for the program. The
initial value of $stdin . |
STDOUT | IO | The actual standard output stream for the program. The
initial value of $stdout . |
TOPLEVEL_BINDING | Binding | A Binding object representing
the binding at Ruby's top level---the level where programs are
initially executed. |
TRUE | TrueClass | Synonym for true . |
%x
.
The value of the string is the standard
output of running the command represented by the string under the
host operating system's standard shell. The execution also sets the
$?
variable with the command's exit status.
filter = "*.c" files = `ls #{filter}` files = %x{ls #{filter}} |
Symbol
object is created by
prefixing an operator, variable, constant, method, class, or module
name with a colon.
The symbol object will be unique for each
different name but does not refer to a particular instance of the
name, so the symbol for (say) :fred
will be the same regardless
of context. A symbol is similar to the concept of atoms in other
high-level languages.
::
'').
barney # variable reference APP_NAMR # constant reference Math::PI # qualified constant reference |
Ruby operators (high to low
precedence)
|
a, b, c = 1, "cat", [ 3, 4, 5 ] |
anObj = A.new anObj.value = "hello" # equivalent to anObj.value=("hello") |
[]=
'') in the receiver, passing as
parameters any indices that appear between the brackets followed by
the rvalue. This is illustrated in Table 18.5 on page 220.
Mapping from element reference to method call
|
Array
, the rvalue is replaced
with the elements of the array, with each element forming its own
rvalue.
Array
, and this array is expanded into a
set of rvalues as described in (1).
a,b=b,a
swaps the values in ``a'' and ``b.''
nil
assigned to them.
begin body end |
begin
and end
.
The value of the block expression is the value of the last expression
executed.
Block expressions also play a role in exception handling, which is discussed
starting on page 235.
false
and nil
. Both of these
values are treated as being false in a boolean context. All other
values are treated as being true.
and
and &&
operators evaluate their first operand. If
false, the expression returns false; otherwise, the expression returns
the value of the second operand.
expr1 and expr2 expr1 && expr2 |
or
and ||
operators evaluate their first operand. If
true, the expression returns true; otherwise, the expression returns
the value of the second operand.
expr1 or expr2 expr1 || expr2 |
not
and !
operators evaluate their operand. If true, the
expression returns false. If false, the expression returns true.
The word forms of these operators (and
, or
, and not
) have
a lower precedence than the corresponding symbol forms (&&
,
||
, and !
). See Table 18.4 on page 219 for details.
The defined?
operator returns nil
if its argument,
which can
be an arbitrary expression, is not defined. Otherwise, it returns a
description of that argument. For examples, see page
78 in the tutorial.
==
, ===
,
<=>
, <
, <=
, >
, >=
, =~
, and the standard
methods eql?
and
equal?
(see Table 7.1 on page 79). All of these operators
are implemented as methods.
Although the operators have intuitive meaning,
it is up to the classes that implement them to produce meaningful
comparison semantics. The library reference starting
on page 275 describes the comparison semantics for the
built-in classes. The module Comparable
provides support for
implementing the operators ==
,
<
, <=
, >
, >=
, and the method between?
in terms of <=>
.
The operator ===
is used in case
expressions, described
on page 223.
Both ==
and =~
have negated forms, !=
and
!~
. Ruby converts these during syntax analysis:
a!=b
is mapped to !(a==b)
, and a!~b
is mapped to !(a =~b)
. There are no methods corresponding to
!=
and !~
.
if expr1 .. expr2 while expr1 ... expr2 |
true
if it is in the set state at the end of
the call, and false
otherwise.
The two-dot form of a range behaves slightly differently than the
three-dot form. When the two-dot form first makes the transition from
unset to set, it immediately evaluates the end condition and makes
the transition accordingly. This means that if expr1 and
expr2 both evaluate to true
on the same call, the
two-dot form will finish the call in the unset state. However, it
still returns true
for this call.
The difference is illustrated by the following code:
a = (11..20).collect {|i| (i%4 == 0)..(i%3 == 0) ? i : nil}
|
||
a
|
» |
[nil, 12, nil, nil, nil, 16, 17, 18, nil, 20]
|
|
||
a = (11..20).collect {|i| (i%4 == 0)...(i%3 == 0) ? i : nil}
|
||
a
|
» |
[nil, 12, 13, 14, 15, 16, 17, 18, nil, 20]
|
Figure not available... |
$_
.
if /re/ ... |
if $_ =~ /re/ ... |
if
and unless
Expressions
if boolean-expression [then] body elsif boolean-expression [then] body else body end |
unless boolean-expression [then] body else body end |
then
keyword separates the body from the condition.
It is
not required if the body starts on a new line.
The value of an if
or unless
expression is the value of the
last expression evaluated in whichever body is executed.
expression if boolean-expression expression unless boolean-expression |
true
(false
for unless
).
boolean-expression ? expr1 : expr2 |
case
Expressions
case target when [ comparison ]+ [then] body when [ comparison ]+ [then] body ... [ else body ] end |
===
target.
When a comparison
returns true, the search stops, and the body associated with the
comparison is executed. case
then returns the value of the last
expression executed. If no comparison matches: if an else
clause is present, its body will be executed; otherwise, case
silently returns nil
.
The then
keyword separates the when
comparisons from the
bodies, and is not needed if the body starts on a new line.
while boolean-expression [do] body end |
until boolean-expression [do] body end |
do
separates boolean-expression from
the body, and may be omitted when the body starts on a new
line.
for [ name ]+ in expression [do] body end |
for
loop is executed as if it were the following
each
loop, except that local variables defined in the body of
the for
loop will be available outside the loop, while those
defined within an iterator block will not.
expression.each do | [ name ]+ | body end |
loop
,
which iterates its associated block, is not
a language construct---it is a method in module Kernel
.
expression while boolean-expression expression until boolean-expression |
begin/end
block,
executes expression zero or more times while boolean-expression
is true
(false
for until
).
If expression is a begin/end
block, the block will always
be executed at least one time.
break
, redo
, next
, and
retry
alter the normal flow through a while
, until
,
for
, or iterator controlled loop.
break
terminates the immediately enclosing loop---control
resumes at the statement following the block. redo
repeats the
loop from the start, but without reevaluating the condition or
fetching the next element (in an iterator). next
skips to the
end of the loop, effectively starting the next iteration.
retry
restarts the loop, reevaluating the condition.
def defname [( [ arg [=val ] ]* [, *vararg ] [, &blockarg ] )] body end |
|
?
''),
exclamation point (``!
''), or equals sign (``=
''). The
question mark and exclamation point are simply part of the name. The
equals sign is also part of the name but additionally signals that
this method is an attribute setter (described
on page 23).
A method definition using an unadorned method name within a class or
module definition creates an instance method. An instance method may
be invoked only by sending its name to a receiver that is an
instance of the class that defined it (or one of that class's subclasses).
Outside a class or module definition, a definition with an unadorned
method name is added as a private method to class Object
, and
hence may be called in any context without an explicit receiver.
A definition using a method name of the form expr.methodname
creates a method associated with the object that is the value
of the expression; the method will be callable only by supplying the
object referenced by the expression as a receiver. Other Ruby
documentation calls these methods singleton methods.
class MyClass def MyClass.method # definition end end |
MyClass.method # call anObject = Object.new def anObject.method # definition end anObject.method # call def (1.class).fred # receiver may be an expression end Fixnum.fred # call |
begin
/end
block, in that it may contain exception handling
statements (rescue
, else
, and ensure
).
def options(a=99, b=a+1)
|
||
[ a, b ]
|
||
end
|
||
options
|
» |
[99, 100]
|
options 1
|
» |
[1, 2]
|
options 2, 4
|
» |
[2, 4]
|
Array
. If the method call specifies any
parameters in excess of the regular argument count, all these extra
parameters will be collected into this newly created array.
def varargs(a, *b)
|
||
[ a, b ]
|
||
end
|
||
varargs 1
|
» |
[1, []]
|
varargs 1, 2
|
» |
[1, [2]]
|
varargs 1, 2, 3
|
» |
[1, [2, 3]]
|
def mixed(a, b=99, *c)
|
||
[ a, b, c]
|
||
end
|
||
mixed 1
|
» |
[1, 99, []]
|
mixed 1, 2
|
» |
[1, 2, []]
|
mixed 1, 2, 3
|
» |
[1, 2, [3]]
|
mixed 1, 2, 3, 4
|
» |
[1, 2, [3, 4]]
|
Proc
and assigned
to the block argument. If no block is present, the argument is set to
nil
.
|
=>
value pairs. These pairs are collected into a
single new Hash
object and passed as a single parameter.
Following these parameters may be a single parameter prefixed with an
asterisk.
If this parameter is an array,
Ruby replaces it with zero
or more parameters corresponding to the elements of the array.
def regular(a, b, *c) # .. end regular 1, 2, 3, 4 regular(1, 2, 3, 4) regular(1, *[2, 3, 4]) |
Proc
or Method
object prefixed with an ampersand character.
Regardless
of the presence of a block argument, Ruby arranges for the value of
the global function
Kernel::block_given?
to reflect the
availability of a block associated with the call.
aProc = proc { 99 } anArray = [ 98, 97, 96 ] def block yield end block { } block do end block(&aProc) def all(a, b, c, *d, &e) puts "a = #{a}" puts "b = #{b}" puts "c = #{c}" puts "d = #{d}" puts "block = #{yield(e)}" end all('test', 1 => 'cat', 2 => 'dog', *anArray, &aProc) |
a = test b = {1=>"cat", 2=>"dog"} c = 98 d = [97, 96] block = 99 |
self
is assumed.
The receiver checks for the
method definition in its own class and then sequentially in its
ancestor classes. The instance methods of included modules act as if
they were in anonymous superclasses of the class that includes them.
If the method is not found, Ruby invokes the method
method_missing
in the receiver. The default behavior
defined in
Kernel::method_missing
is to report an error and
terminate the program.
When a receiver is explicitly specified in a method invocation, it may
be separated from the method name using either a period ``.
'' or
two colons ``::
''.
The only difference between these two forms
occurs if the method name starts with an uppercase letter. In this
case, Ruby will assume that a receiver::Thing
method call is
actually an attempt to access a constant called Thing
in the
receiver unless the method invocation has a parameter list between
parentheses.
Foo.Bar() # method call Foo.Bar # method call Foo::Bar() # method call Foo::Bar # constant access |
return [ expr ]* |
return
expression immediately exits a method. The value of a
return
is nil
if it is called with no parameters, the value of
its parameter if it is called with one parameter, or an array containing all of
its parameters if it is called with more than one parameter.
super [ ( [ param ]* [*array ] ) ] [ block ] |
super
acts just like a
call to that original method, except that the search for a method body
starts in the superclass of the object that was found to contain the
original method. If no parameters (and no parentheses) are passed to
super
, the original method's parameters will be passed; otherwise,
the parameters to super
will be passed.
expr1 operator operator expr1 expr1 operator expr2 |
(expr1).operator(expr2) |
receiver.attrname = rvalue |
receiver [ expr ]+ receiver [ expr ]+ = rvalue |
[]
in the receiver, passing as parameters the expressions between
the brackets.
When used as an lvalue, element reference invokes the method []=
in
the receiver, passing as parameters the expressions between
the brackets, followed by the rvalue being assigned.
alias newName oldName |
$&
, $'
, $'
, and $+
). Local variables,
instance variables, class variables, and constants may not be
aliased. The parameters to alias
may be names or symbols.
class Fixnum
|
||
alias plus +
|
||
end
|
||
1.plus(3)
|
» |
4
|
|
||
alias $prematch $`
|
||
"string" =~ /i/
|
» |
3
|
$prematch
|
» |
"str"
|
|
||
alias :cmd :`
|
||
cmd "date"
|
» |
"Sun Nov 25 23:44:19 CST 2001\n"
|
def meth
|
||
"original method"
|
||
end
|
||
|
||
alias original meth
|
||
|
||
def meth
|
||
"new and improved"
|
||
end
|
||
meth
|
» |
"new and improved"
|
original
|
» |
"original method"
|
class classname [< superexpr ] body end class << anObject body end |
Class
by executing the code in body.
In the first form, a
named class is created or extended. The resulting Class
object is
assigned to a global constant named classname. This name should
start with an uppercase letter. In the second form, an anonymous
(singleton) class is associated with the specific object.
If present, superexpr should be an expression that evaluates to a
Class
object that will be installed as the superclass of the class
being defined. If omitted, it defaults to class Object
.
Within body, most Ruby expressions are simply executed as the
definition is read. However:
::
'' to qualify their names.
module NameSpace class Example CONST = 123 end end obj = NameSpace::Example.new a = NameSpace::Example::CONST |
Module#include
method will add the named modules as
anonymous superclasses of the class being defined.
attr
and include
) are actually simply private instance methods of
class Module
(documented starting on page 344).
Chapter 19, which begins
on page 237, describes in more detail how
Class
objects interact with the rest of the environment.
obj = classexpr.new [ ( [ args ]* ) ] |
Class
defines the instance method
Class#new
, which:
initialize
in the newly created
object, passing it any arguments originally passed to new
.
new
without
calling super
, no objects of that class can be created.
Module
that
create accessor methods automatically.
class name attr attribute [, writable ] attr_reader [ attribute ]+ attr_writer [ attribute ]+ attr_accessor [ attribute ]+ end |
module name body end |
Module
object is stored in a constant. A module may contain
class and instance methods and may define constants and class
variables. As with classes, module methods are invoked using the
Module
object as a receiver, and constants are accessed using the
``::
'' scope resolution operator.
module Mod CONST = 1 def Mod.method1 # module method CONST + 1 end end |
Mod::CONST
|
» |
1
|
Mod.method1
|
» |
2
|
class|module name include expr end |
include
method. The module or class definition
containing the include
gains access to the constants, class
variables, and instance methods of the module it includes.
If a module is included within a class definition, the module's
constants, class variables, and instance methods are effectively
bundled into an anonymous (and inaccessible) superclass for that
class. In particular, objects of the class will respond to messages
sent to the module's instance methods.
A module may also be included at the top level, in which case the
module's constants, class variables, and instance methods become
available at the top level.
include
is useful for providing mixin functionality,
it is also a way of bringing the constants, class variables, and
instance methods of a module into another namespace. However,
functionality defined in an instance method will not be available as a
module method.
module Math def sin(x) # end end # Only way to access Math.sin is... include Math sin(1) |
Module#module_function
solves this problem by taking one or
more module instance methods and copying their definitions into
corresponding module methods.
module Math def sin(x) # end module_function :sin end Math.sin(1) include Math sin(1) |
module_function
,
not aliased.
self
as the receiver). Private methods
therefore can be called only in the defining class and by direct
descendents within the same object.
private [ aSymbol ]* protected [ aSymbol ]* public [ aSymbol ]* |
do
/end
pair. The block may start with an argument list
between vertical bars. A code block may appear only immediately after a
method invocation. The start of the block must be on the same logical
line as the end of the invocation.
invocation do | a1, a2, ... | end invocation { | a1, a2, ... | } |
do
has a low
precedence. If the method invocation has parameters that are not
enclosed in parentheses, the brace form of a block will bind to the
last parameter, not to the overall invocation. The do
form will
bind to the invocation.
Within the body of the invoked method, the code block may be called
using the yield
method.
Parameters passed to the
yield
will be assigned to arguments in the block using the
rules of parallel assignment described starting on page 219.
The return value of the yield
is the value of the last
expression evaluated in the block.
A code block remembers the environment in which it was defined, and it
uses that environment whenever it is called.
Proc
using the
methods
Proc.new
and
Kernel#proc
, or by associating the block
with a method's block argument.
The Proc
constructor takes an associated block and wraps it with
enough context to be able to re-create the block's environment when it
is subsequently called. The
Proc#call
instance method then
allows you to invoke the original block, optionally passing in
parameters. The code in the block (and the associated closure)
remains available for the lifetime of the Proc
object.
If the last argument in a method's argument list is prefixed with an
ampersand (``&
''), any block associated with calls to that method
will be converted to a Proc
object and assigned to that parameter.
Exception
and its
descendents (a full list of the built-in exceptions is given in Figure
22.1 on page 299).
Kernel::raise
method raises an exception.
raise raise aString raise thing [, aString [ aStackTrace ] ] |
$!
or a new
RuntimeError
if $!
is nil
.
The second form creates a new RuntimeError
exception, setting its
message to the given string.
The third form creates an exception object by invoking the method
exception
on its first argument. It then sets this
exception's message and backtrace to its second and third arguments.
Class Exception
and objects of class Exception
contain factory
methods called exception
, so an exception class name or
instance can be used as the first parameter to raise
.
When an exception is raised, Ruby places a reference to the
Exception
object in the global variable $!
.
begin
/end
block.
begin code... code... [rescue [parm]* [=> var ] [then] error handling code... ]* [else no exception code... ] [ensure always executed code... ] end |
rescue
clauses, and each rescue
clause may specify zero or more parameters. A rescue
clause with
no parameter is treated as if it had a parameter of
StandardError
.
When an exception is raised, Ruby scans up the call stack until it
finds an enclosing begin
/end
block. For each rescue
clause in that block, Ruby compares the raised exception against each
of the rescue clause's parameters in turn; each parameter is tested using
$!.kind_of?(parameter)
. If the raised exception matches
a rescue
parameter, Ruby executes the body of the rescue
and
stops looking. If a matching rescue
clause ends with =>
and
a variable name, the variable is set to $!
.
Although the parameters to the rescue
clause are typically the
names of Exception
classes, they can actually be arbitrary
expressions (including method calls) that return an appropriate class.
If no rescue clause matches the raised exception, Ruby moves up the stack
frame looking for a higher-level begin
/end
block that
matches. If an exception propagates to the top level without being
rescued, the program terminates with a message.
If an else
clause is present,
its body is executed if no
exceptions were raised in initial code.
Exceptions raised during the execution of the else
clause are not
captured by rescue
clauses in the same block as the else
.
If an ensure
clause is present,
its body is always executed
as the block is exited (even if an uncaught exception is in the
process of being propagated).
retry
statement can be used within a rescue
clause to restart the enclosing begin
/end
block from the beginning.
Kernel::catch
executes its associated block.
catch ( aSymbol | aString ) do block... end |
Kernel::throw
interrupts the normal processing of
statements.
throw( aSymbol | aString [, anObject ] ) |
throw
is executed, Ruby searches up the call stack for the
first catch
block with a matching symbol or string. If it is found,
the search stops, and execution resumes past the end of the catch
's
block. If the throw
was passed a second parameter, that value
is returned as the value of the catch
. Ruby honors the
ensure
clauses of any block expressions it traverses while
looking for a corresponding catch
.
If no catch
block matches the throw
, Ruby raises a NameError
exception at the location of the throw
.
Previous < |
Contents ^
|
Next >
|