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
http://www.ruby-lang.org) is a good starting
pointing as it offers Ruby tutorials and the Ruby Language FAQ.
def factorial(n)
if n == 0
return 1
else
return n * factorial(n-1)
end
end
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
# 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
ruby [ options ] [鈥擼 [ programfile ] [ argument... ]
-a-n or -p to split each
line. Split output is stored in $F.
-c-C dir-X).
-d-debug). Sets
$DEBUG to true.
-e prog-e options for
multiline programs.
-F pat$;) used by split.
-h-help).
-i [ext]-I dir-K [kcode]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-nwhile gets; ... end).
-0[octal]$/) as an octal.
Defaults to \0 if octal
not specified.
-p$_ for
each iteration.
-r librequire to load lib as
a library before executing.
-s-SPATH.
-T [level]ruby [ options ] [鈥擼 [ programfile ] [ argument... ]
-a-n or -p to split each
line. Split output is stored in $F.
-c-C dir-X).
-d-debug). Sets
$DEBUG to true.
-e prog-e options for
multiline programs.
-F pat$;) used by split.
-h-help).
-i [ext]-I dir-K [kcode]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-nwhile gets; ... end).
-0[octal]$/) as an octal.
Defaults to \0 if octal
not specified.
-p$_ for
each iteration.
-r librequire to load lib as
a library before executing.
-s-SPATH.
-T [level]$SAFE variable.
-vverbose mode (equivalent to
--verbose).
-wprogramfileENV object contains a list of current environment
variables.
DLN_LIBRARY_PATHHOMEDir::chdir.
Also used by File::expand_path to expand
"~".
LOGDIRDir::chdir and environment variable
HOME isn't set.
PATH-S
option. Separate each path with a colon (semicolon in DOS and
Windows).
RUBYLIBRUBYLIB_PREFIXRUBYLIB is:
/usr/local/lib/ruby/site_ruby
RUBYLIB_PREFIX is:/usr/local/lib/ruby;f:/ruby
f:/ruby/site_ruby. Works only with
DOS, Windows, and OS/2 versions.
RUBYOPT$SAFE is greater than 0).
RUBYPATH-S option, search
path for Ruby programs. Takes precedence over
PATH. Ignored in taint mode (where
$SAFE is greater than 0).
RUBYSHELLSHELL or COMSPEC are
checked.
-w option is enabled.
a + ba+b (a is a
local variable)
a +ba(+b) (a, in
this case, is a method call)
+, -, or backslash at the end
of a line, they indicate the continuation of a statement.
# to the end of the line.
# This is a comment.
=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
( _ ). You can distinguish a
variable's type by the initial character of its identifier.
BEGIN |
do |
next |
then |
END |
else |
Fixnum,
Bignum, and Float.
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
Float:
123.4 # floating point value 1.0e6 # scientific notation 4E20 # dot not required 4e+20 # sign before exponential
String:
"abc"'abc'\\ and
\'.
"foo" "bar" # means "foobar"
#$var and #@var are
abbreviated forms of #{$var} and
#{@var}. Embeds value of expression in
#{...} into a string.
|
Sequence
|
Character represented
|
|---|---|
\n |
Newline (0x0a)
|
\r |
Carriage return (0x0d)
|
\f |
Formfeed (0x0c)
|
\b |
Backspace (0x08) |
$. 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.
@. Uninitialized instance variables have the value
nil (and produce warnings with the
-w option).
@@ 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.
_. 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.
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.
+ -
* / %
** & |
^ <<
>> &&
||), there is a corresponding form of abbreviated
assignment operator (+= -=
etc.)
:
::[] ** +(unary) -(unary) ! ~* / % + -<< >>&| ^> >= < <=<=> == === != =~ !~&&||.. ...?:= (and abbreviated assignment operators such as +=, -=, etc.)notand or...!not&&and||or::=+=, -=, (and other abbreviated assignment operators)? : (ternary operator)if expressions, and while
loops.
true from the point
right operand is true until left operand is
true:
.. expr2true.
... expr2true.
.. expr2<= x
<= expr2)
... expr2<=
x <
expr2)
&& andtrue 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.
|| ortrue if either operand is
*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.self. This is the only form by which private methods may be called.Math.sin(1.0)
include Math sin(1.0)
! 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.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
code if conditional is true.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 conditionalExecutes code unless conditional is
true.
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.
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
true.begin code end while conditional
while modifier
follows a begin statement with no
rescue or ensure clauses,
code is executed once before
conditional is evaluated.
false.
An until statement's
conditional is separated from code by the
reserved word 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 statements
introduce a new scope for local variables.
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.
$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
}
IO, environment
variables, and ARGV is automatically flagged as
tainted.
PATH is an exception. Its value is checked, and
tainted only if any directory in it is writable by everybody.
RUBYLIB and RUBYOPT are ignored
at startup.
$LOAD_PATH.
$!=> in rescue
clause.
$@stack backtrace for the last exception raised.
The stack backtrace information can retrieved by
Exception#backtrace method of the last exception.
$/gets, readline, etc., take
their input record separator as optional argument.
$\nil by default).$,Array#join (nil by default).
You can specify separator explicitly to
Array#join.
$;split
(nil by default). You can specify separator
explicitly for String#split.
$.ARGF.lineno.
$<ARGF.$>$defout.$0$$process.pid of the current Ruby program being
executed.
$?$:$LOAD_PATH.$DEBUG-d or --debug
command-line option is specified.
$defoutprint and
printf ($stdout by default).
$Fsplit
when -a is specified. This variable is set if the
-a command-line option is specified along with the
-p or -n option.
$FILENAMEARGF. Equivalent to
ARGF.filename.
$LOAD_PATH$!=> in rescue
clause.
$@stack backtrace for the last exception raised.
The stack backtrace information can retrieved by
Exception#backtrace method of the last exception.
$/gets, readline, etc., take
their input record separator as optional argument.
$\nil by default).$,Array#join (nil by default).
You can specify separator explicitly to
Array#join.
$;split
(nil by default). You can specify separator
explicitly for String#split.
$.ARGF.lineno.
$<ARGF.$>$defout.$0$$process.pid of the current Ruby program being
executed.
$?$:$LOAD_PATH.$DEBUG-d or --debug
command-line option is specified.
$defoutprint and
printf ($stdout by default).
$Fsplit
when -a is specified. This variable is set if the
-a command-line option is specified along with the
-p or -n option.
$FILENAMEARGF. Equivalent to
ARGF.filename.
$LOAD_PATH$SAFETRUE, FALSE, and
NIL are backward-compatible. It's preferable
to use true, false, and
nil.
TRUEtrue.FALSEfalse.NILnil.ARGF$<.
ARGV$*.
DATAEND__ directive. Not defined if __END__ isn't present in code.
ENVENV can be handled as a hash.
RUBY_PLATFORMi686-linux.
RUBY_RELEASE_DATE2001-09-19.
RUBY_VERSION1.6.5.
STDERR$stderr.
STDIN$stdin.STDOUT$stdout.TOPLEVEL_BINDINGBinding object at Ruby's top level.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$! isn't nil), its error
message is displayed.
Array(obj)to_ary or to_a.
at_exit {...}END statement (referenced in Section 2.8), but END statement
registers the block only once.
autoload(classname, file)autoload :Foo, "foolib.rb".
bindingBinding object that is returned may be passed to
the eval method as its second argument.
block_given?true if the method was called with a block.callcc {|c|...}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]):line.
If n is specified, returns stack entries
from nth level on down.
catch(tag) {...}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=$/])$_ 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=$/])$_, modifying the string in
place.
String), operating system
services and abstractions (IO,
File, Process, etc.), numbers
(Integer, Fixnum, etc.), and so
on.
Object class.
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.
Kernelinitializenew method are
passed directly to initialize. It's assumed
that this method will be redefined by subclasses for object
initialization.
Kernel
is the module in which Ruby's built-in functions are defined as
module functions. Since it's included in
Object, Kernel is indirectly
included in all classes.