SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
Ruby QuickRef

11/29/2005 12:35 AM

Sitemap | Search || Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef

Ruby QuickRef
Contents:
Contents
Language
General Syntax Rules
Reserved words
Types
Numbers
Strings
Backslashes
Here Docs
Ranges
Regexen
Arrays
Hashes
Files
Mode Strings
Variables
Pseudo variables
Pre-defined variables
Pre-defined global constants
Expressions
Terms
Operators and Precedence
Control Expressions
Invoking a Method
Defining a Class
Defining a Module
Defining a Method
Access Restriction
Accessors
Aliasing
Blocks, Closures, and Procs
Blocks/Closures
Proc Objects
Exceptions, Catch, and Throw
Standard Library
Built-in Library
Class Hierarchy
Modules
Standard Library
Tools
ruby
Command Line Options
Environment Variables
irb
xmp
ruby-mode
Debugger
rdoc
Mindshare, Idiom and Patterns
Object Design
Visitor Pattern
Class SimpleDelegator, DelegateClass
Module Observer
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 1 of 14
Ruby QuickRef

11/29/2005 12:35 AM

Module Singleton
Other Third-party Libraries
Racc
Test::Unit

Language
General Syntax Rules
Comments start with a pound/sharp (#) character and go to EOL.
Ruby programs are sequence of expressions.
Each expression is delimited by semicolons(;) or newlines unless obviously incomplete (e.g. trailing '+').
Backslashes at the end of line does not terminate expression.

Reserved words
alias
do
in
return
while

and
else
module
self
yield

BEGIN
elsif
next
super

begin
END
nil
then

break
end
not
true

case
ensure
or
undef

class
false
redo
unless

def
for
rescue
until

defined
if
retry
when

Types
Basic types are numbers, strings, ranges, regexen, symbols, arrays, and hashes. Also included are files because they
are used so often.
Numbers
123 1_234 123.45 1.2e-3 0xffff (hex) 0b01011 (binary) 0377 (octal)
?a
ASCII character
?C-a
Control-a
?M-a
Meta-a
?M-C-a Meta-Control-a
:symbol Integer corresponding to identifiers, variables, and operators.

Strings
In all of the %() cases below, you may use any matching characters or any single character for delimiters. %[], %!!,
%@@, etc.
'no interpolation'
"#{interpolation}, and backslashesn"
%q(no interpolation)
%Q(interpolation and backslashes)
%(interpolation and backslashes)
`echo command interpretation with interpolation and backslashes`
%x(echo command interpretation with interpolation and backslashes)
Backslashes
t (tab), n (newline), r (carriage return), f (form feed), b
(backspace), a (bell), e (escape), s (whitespace), nnn (octal),
xnn (hexadecimal), cx (control x), C-x (control x), M-x (meta x),
M-C-x (meta control x)
Here Docs
<<identifier
<<"identifier"
<<'identifier'
<<-identifier

-

interpolated, goes until identifier
same thing
no interpolation
you can indent the identifier by using "-" in front

Ranges
1..10
'a'..'z'
(1..10) === 5 => true
(1..10) === 15 => false
while gets # prints lines starting at 'start' and ending at 'end'
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 2 of 14
Ruby QuickRef

11/29/2005 12:35 AM

while gets # prints lines starting at 'start' and ending at 'end'
print if /start/../end/
end
class RangeThingy
# ...
def <=>(rhs)
# ...
end
def succ
# ...
end
end
range = RangeThingy.new(lower_bound)..RangeThingy.new(upper_bound)

Regexen
/normal regex/iomx[neus]
%r|alternate form|

options:
/i
/o
/m
/x
/[neus]

case insensitive
case insensitive
multiline mode - '.' will match newline
extended mode - whitespace is ignored
encoding: none, EUC, UTF-8, SJIS, respectively

regex characters:
.
[ ]
[^ ]
*
*?
+
+?
?
|
( )
^
$
#{m,n}
#{m,n}?
A
b
B
b
d
D
S
s
W
w
z
Z
(?# )
(?: )
(?= )
(?! )
(?ix-ix)
(?ix-ix: )

any character except newline
any single character of set
any single character NOT of set
0 or more previous regular expression
0 or more previous regular expression(non greedy)
1 or more previous regular expression
1 or more previous regular expression(non greedy)
0 or 1 previous regular expression
alternation
grouping regular expressions
beginning of a line or string
end of a line or string
at least m but most n previous regular expression
at least m but most n previous regular expression(non greedy)
beginning of a string
backspace(0x08)(inside[]only)
non-word boundary
word boundary(outside[]only)
digit, same as[0-9]
non-digit
non-whitespace character
whitespace character[ tnrf]
non-word character
word character[0-9A-Za-z_]
end of a string
end of a string, or before newline at the end
comment
grouping without backreferences
zero-width positive look-ahead assertion
zero-width negative look-ahead assertion
turns on/off i/x options, localized in group if any.
turns on/off i/x options, localized in non-capturing group.

Arrays
[1, 2, 3]
%w(foo bar baz)
%W(foo bar baz #{var})

Indexes may be negative, and they index backwards (eg -1 is last element).
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 3 of 14
Ruby QuickRef

11/29/2005 12:35 AM

Hashes
{1=>2, 2=>4, 3=>6}
{ expr => expr...}

Files
Common methods include:
File.join(p1, p2, ... pN) => "p1/p2/.../pN" platform independent paths
File.new(path, modestring="r") => file
File.new(path, modenum [, permnum]) => file
File.open(fileName, aModeString="r") {|file| block} -> nil
File.open(fileName [, aModeNum [, aPermNum ]]) {|file| block} -> nil
IO.foreach(path, sepstring=$/) {|line| block}
IO.readlines(path) => array
Mode Strings

r
Read-only, starts at beginning of file (default mode).
r+
Read-write, starts at beginning of file.
w
Write-only, truncates existing file to zero length or creates a new file for writing.
w+
Read-write, truncates existing file to zero length or creates a new file for reading and writing.
a
Write-only, starts at end of file if file exists, otherwise creates a new file for writing.
a+
Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.
b
(DOS/Windows only) Binary file mode (may appear with any of the key letters listed above).

Variables
$global_variable
@instance_variable
[OtherClass::]CONSTANT
local_variable

Pseudo variables
self
nil
true
false
__FILE__
__LINE__

the
the
the
the
the
the

receiver of the current method
sole instance of the Class NilClass(represents false)
sole instance of the Class TrueClass(typical true value)
sole instance of the Class FalseClass(represents false)
current source file name.
current line number in the source file.

Pre-defined variables
$!
$@
$&
$`
$'
$+
$1
$~
$=
$/
$
$,
$;
$.
$<

The exception information message set by 'raise'.
Array of backtrace of the last exception thrown.
The string matched by the last successful pattern match in this scope.
The string to the left of the last successful match.
The string to the right of the last successful match.
The last bracket matched by the last successful match.
The Nth group of the last successful match. May be > 1.
The information about the last match in the current scope.
The flag for case insensitive, nil by default.
The input record separator, newline by default.
The output record separator for the print and IO#write. Default is nil.
The output field separator for the print and Array#join.
The default separator for String#split.
The current input line number of the last file that was read.
The virtual concatenation file of the files given on command line.

http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 4 of 14
Ruby QuickRef

$>
$_
$0
$*
$$
$?
$:
$"
$DEBUG
$FILENAME
$LOAD_PATH
$stderr
$stdin
$stdout
$VERBOSE
$-0
$-a
$-d
$-F
$-i
$-I
$-l
$-p
$-v

11/29/2005 12:35 AM

The default output for print, printf. $stdout by default.
The last input line of string by gets or readline.
Contains the name of the script being executed. May be assignable.
Command line arguments given for the script sans args.
The process number of the Ruby running this script.
The status of the last executed child process.
Load path for scripts and binary modules by load or require.
The array contains the module names loaded by require.
The status of the -d switch.
Current input file from $<. Same as $<.filename.
The alias to the $:.
The current standard error output.
The current standard input.
The current standard output.
The verbose flag, which is set by the -v switch.
The alias to $/.
True if option -a is set. Read-only variable.
The alias to $DEBUG.
The alias to $;.
In in-place-edit mode, this variable holds the extention, otherwise nil.
The alias to $:.
True if option -l is set. Read-only variable.
True if option -p is set. Read-only variable.
The alias to $VERBOSE.

Pre-defined global constants
TRUE
FALSE
NIL
STDIN
STDOUT
STDERR
ENV
ARGF
ARGV
DATA
RUBY_VERSION
RUBY_RELEASE_DATE
RUBY_PLATFORM

The
The
The
The
The
The
The
The
The
The
The
The
The

typical true value.
false itself.
nil itself.
standard input. The default value for $stdin.
standard output. The default value for $stdout.
standard error output. The default value for $stderr.
hash contains current environment variables.
alias to the $<.
alias to the $*.
file object of the script, pointing just after __END__.
ruby version string (VERSION was depricated).
relase date string.
platform identifier.

Expressions
Terms
Terms are expressions that may be a basic type (listed above), a shell command, variable reference, constant
reference, or method invocation.
Operators and Precedence
(Top to bottom)
::
[]
**
-(unary) +(unary) ! ~
* / %
+ << >>
&
| ^
> >= < <=
<=> == === != =~ !~
&&
||
.. ...
=(+=, -=...)
not
and or

All of the above are just methods except these:
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 5 of 14
Ruby QuickRef

11/29/2005 12:35 AM

=, .., ..., !, not, &&, and, ||, or, !=, !~

In addition, assignment operators(+= etc.) are not user-definable.
Control Expressions
if bool-expr [then]
body
elsif bool-expr [then]
body
else
body
end
unless bool-expr [then]
body
else
body
end
expr if
bool-expr
expr unless bool-expr
case target-expr
when comparison [, comparison]... [then]
body
when comparison [, comparison]... [then]
body
...
[else
body]
end

(comparisons may be regexen)
while bool-expr [do]
body
end
until bool-expr [do]
body
end
begin
body
end while bool-expr
begin
body
end until bool-expr
for name[, name]... in expr [do]
body
end
expr.each do | name[, name]... |
body
end
expr while bool-expr
expr until bool-expr

break terminates loop immediately.
redo immediately repeats w/o rerunning the condition.
next starts the next iteration through the loop.
retry restarts the loop, rerunning the condition.

Invoking a Method
Nearly everything available in a method invocation is optional, consequently the syntax is very difficult to follow.
Here are some examples:
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 6 of 14
Ruby QuickRef

11/29/2005 12:35 AM

method
obj.method
Class::method
method(arg1, arg2)
method(arg1, key1 => val1, key2 => val2, aval1, aval2) #{ block }
method(arg1, *[arg2, arg3]) becomes: method(arg1, arg2, arg3)
invocation := [receiver ('::' | '.')] name [ parameters ] [ block ]
parameters := ( [param]* [, hashlist] [*array] [&aProc] )
block
:= { blockbody } | do blockbody end

Defining a Class
Classnames begin w/ capital character.
class Identifier [< superclass ]
expr..
end
# singleton classes, add methods to a single instance
class << obj
expr..
end

Defining a Module
module Identifier
expr..
end

Defining a Method
def method_name(arg_list, *list_expr, &block_expr)
expr..
end
# singleton method
def expr.identifier(arg_list, *list_expr, &block_expr)
expr..
end

All items of the arg list, including parens, are optional.
Arguments may have default values (name=expr).
Method_name may be operators (see above).
The method definitions can not be nested.
Methods may override operators: .., |, ^, &, <=>, ==, ===, =~, >, >=, <, <=, +, -, *, /, %, **, <<, >>, ~, +@, -@, [], []=
(2 args)
Access Restriction
public - totally accessable.
protected - accessable only by instances of class and direct descendants. Even through hasA relationships. (see below)
private - accessable only by instances of class.
Restriction used w/o arguments set the default access control.
Used with arguments, sets the access of the named methods and constants.
class A
protected
def protected_method
# nothing
end
end
class B < A
public
def test_protected
myA = A.new
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 7 of 14
Ruby QuickRef

11/29/2005 12:35 AM

myA.protected_method
end
end
b = B.new.test_protected

Accessors
Class Module provides the following utility methods:
attr_reader <attribute>[, <attribute>]...
Creates a read-only accessor for each <attribute>.
attr_writer <attribute>[, <attribute>]...
Creates a write-only accessor for each <attribute>.
attr <attribute> [, <writable>]
Equivalent to "attr_reader <attribute>; attr_writer <attribute> if <writable>"
attr_accessor <attribute>[, <attribute>]...
Equivalent to "attr <attribute>, TRUE" for each argument.

Aliasing
alias
:old :new
alias_method :new, :old

Creates a new reference to whatever old referred to. old can be any existing method, operator, global. It may not be a
local, instance, constant, or class variable.

Blocks, Closures, and Procs
Blocks/Closures
blocks must follow a method invocation:
invocation do ... end
invocation { ... }

Blocks remember their variable context, and are full closures.
Blocks are invoked via yield and may be passed arguments.
Brace form has higher precidence and will bind to the last parameter if invocation made w/o parens.
do/end form has lower precidence and will bind to the invocation even without parens.
Proc Objects
Created via:
Kernel#proc
Proc#new
By invoking a method w/ a block argument.
See class Proc for more information.

Exceptions, Catch, and Throw
Exception
StandardError
LocalJumpError
SystemStackError
ZeroDivisionError
RangeError
FloatDomainError
SecurityError
ThreadError
IOError
EOFError
ArgumentError
IndexError
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 8 of 14
Ruby QuickRef

11/29/2005 12:35 AM

RuntimeError
TypeError
SystemCallError
Errno::*
RegexpError
SignalException
Interrupt
fatal
NoMemoryError
ScriptError
LoadError
NameError
SyntaxError
NotImplementedError
SystemExit
begin
expr..
[rescue [error_type [=> var],..]
expr..]..
[else
expr..]
[ensure
expr..]
end

The default error_type for resuce is StandardError, not Exception.

Standard Library
Ruby comes with an extensive library of classes and modules. Some are built-in, and some are part of the standard
library. You can distinguish the two by the fact that the built-in classes are in fact, built-in. There are no dot-rb files
for them.

Built-in Library
Class Hierarchy
Object
Hash
Symbol
IO
File
Continuation
File::Stat
Data
NilClass
Exception (see tree above)
Array
Proc
String
Numeric
Float
Integer
Bignum
Fixnum
Regexp
Thread
Module
Class
ThreadGroup
Method
UnboundMethod
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 9 of 14
Ruby QuickRef

11/29/2005 12:35 AM

Struct
Struct::Tms
TrueClass
Time
Dir
Binding
Range
MatchData
FalseClass
Modules
Comparable
Enumerable
Errno
FileTest
GC
Kernel
Marshal
Math
ObjectSpace
Precision
Process

Standard Library
The essentials:
benchmark.rb a simple benchmarking utility
cgi-lib.rb decode CGI data - simpler than cgi.rb
cgi.rb CGI interaction
date.rb date object (compatible)
debug.rb ruby debugger
delegate.rb delegate messages to other object
English.rb access global variables by english names
fileutils.rb file utility methods for copying, moving, removing, etc.
find.rb traverse directory tree
jcode.rb UTF-8 and Japanese String helpers (replaces String methods)
net/*.rb Networking classes of all kinds
observer.rb observer desing pattern library (provides Observable)
open-uri.rb good wrapper for net/http, net/https and net/ftp
open3.rb open subprocess connection stdin/stdout/stderr
ostruct.rb python style object (freeform assignment to instance vars)
parsearg.rb argument parser using getopts
pp prettier debugging output, 'p' on steroids.
profile.rb ruby profiler - find that slow code!
pstore.rb persistent object strage using marshal
rexml/*.rb XML toolkit
singleton.rb singleton design pattern library
stringio lets you use an IO attached to a string.
tempfile.rb temporary file that automatically removed
test/unit unit testing framework
time.rb extension to Time class with a lot of converters
tracer.rb execution tracer
webrick Fairly spiffy web server
yaml alternative readable serialization format

Tools
ruby
Command Line Options

http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 10 of 14
Ruby QuickRef

-0[octal]
-a
-c
-Cdirectory
--copyright
-d
-e 'command'
-F regexp
-h
-i[extension]
-Idirectory
-Kkcode
-l
-n
-p
-rlibrary
-s
-S
-T[level]
-v
--version
-w
-x[directory]
-X directory
-y

11/29/2005 12:35 AM

specify record separator (0, if no argument).
autosplit mode with -n or -p (splits $_ into $F).
check syntax only.
cd to directory, before executing your script.
print the copyright and exit.
set debugging flags (set $DEBUG to true).
one line of script. Several -e's allowed.
split() pattern for autosplit (-a).
prints summary of the options.
edit ARGV files in place (make backup if extension supplied).
specify $LOAD_PATH directory (may be used more than once).
specifies KANJI (Japanese) code-set.
enable line ending processing.
assume 'while gets(); ... end' loop around your script.
assume loop like -n but print line also like sed.
require the library, before executing your script.
enable some switch parsing for switches after script name.
look for the script using PATH environment variable.
turn on tainting checks.
print version number, then turn on verbose mode.
print the version and exit.
turn warnings on for your script.
strip off text before #! line and perhaps cd to directory.
causes Ruby to switch to the directory.
turns on compiler debug mode.

Environment Variables
DLN_LIBRARY_PATH
RUBYLIB
RUBYLIB_PREFIX
RUBYOPT
RUBYPATH
RUBYSHELL

Search path for dynamically loaded modules.
Additional search paths.
Add this prefix to each item in RUBYLIB. Windows only.
Additional command line options.
With -S, searches PATH, or this value for ruby programs.
Shell to use when spawning.

irb
irb [options] [script [args]]

The essential options are:
-d
-f
-h
-m
-r module
-v
--inf-ruby-mode
--inspect
--noinspect
--noprompt
--noreadline
--prompt
--readline
--tracer

Sets $DEBUG to true. Same as "ruby -d ..."
Prevents the loading of ~/.irb.rc.
Get a full list of options.
Math mode. Overrides --inspect. Loads "mathn.rb".
Loads a module. Same as "ruby -r module ..."
Prints the version and exits.
Turns on emacs support and turns off readline.
Turns on inspect mode. Default.
Turns off inspect mode.
Turns off the prompt.
Turns off readline support.
Sets to one of 'default', 'xmp', 'simple', or 'inf-ruby'.
Turns on readline support. Default.
Turns on trace mode.

Besides arbitrary ruby commands, the special commands are:
exit
fork block
cb args
source file
irb [obj]
conf[.key[= val]]
jobs
fg session
kill session

exits the current session, or the program
forks and runs the given block
changes to a secified binding
loads a ruby file into the session
starts a new session, with obj as self, if specified
access the configuration of the session
lists the known sessions
switches to the specifed session
kills a specified session

Session may be specified via session#, thread-id, obj, or self.

http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 11 of 14
Ruby QuickRef

11/29/2005 12:35 AM

xmp
require "irb/xmp"
xmp "something to eval" # or:
x = XMP.new
x.puts "something to eval"

ruby-mode
TODO: I don't have a freakin clue how to use the inferior ruby thing... I always fire up a shell in emacs... DOH!

Debugger
To invoke the debugger:
ruby -r debug ...

To use the debugger:
b[reak] [file:|class:]<line|method
b[reak] [class.]<line|method
set breakpoint to some position
wat[ch] expression
set watchpoint to some expression
cat[ch] exception
set catchpoint to an exception
b[reak]
list breakpoints
cat[ch]
show catchpoint
del[ete][ nnn]
delete some or all breakpoints
disp[lay] expression
add expression into display expression list
undisp[lay][ nnn]
delete one particular or all display expressions
c[ont]
run until program ends or hit breakpoint
s[tep][ nnn]
step (into methods) one line or till line nnn
n[ext][ nnn]
go over one line or till line nnn
w[here]
display frames
f[rame]
alias for where
l[ist][ (-|nn-mm)]
list program, - lists backwards
nn-mm lists given lines
up[ nn]
move to higher frame
down[ nn]
move to lower frame
fin[ish]
return to outer frame
tr[ace] (on|off)
set trace mode of current thread
tr[ace] (on|off) all
set trace mode of all threads
q[uit]
exit from debugger
v[ar] g[lobal]
show global variables
v[ar] l[ocal]
show local variables
v[ar] i[nstance] object
show instance variables of object
v[ar] c[onst] object
show constants of object
m[ethod] i[nstance] obj
show methods of object
m[ethod] class|module
show instance methods of class or module
th[read] l[ist]
list all threads
th[read] c[ur[rent]]
show current thread
th[read] [sw[itch]] nnn
switch thread context to nnn
th[read] stop nnn
stop thread nnn
th[read] resume nnn
resume thread nnn
p expression
evaluate expression and print its value
h[elp]
print this help
everything else
evaluate
empty
repeats the last command

rdoc
=begin
the everything between a line beginning with `=begin' and
that with `=end' will be skipped by the interpreter.
=end

FIX: there is a lot more to rdoc.

Mindshare, Idiom and Patterns
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 12 of 14
Ruby QuickRef

11/29/2005 12:35 AM

Object Design
Visitor Pattern
By defining the method #each and including Enumerable, you get to use all the methods in Enumerable:
class Mailbox
include Enumerable
# ...
def each
@mail.each do
# ...
yield
end
end
end

Class SimpleDelegator, DelegateClass
foo = Object.new
foo2 = SimpleDelegator.new(foo)
foo.hash == foo2.hash # => false
Foo = DelegateClass(Array)
class ExtArray<DelegateClass(Array)
...
end

Module Observer
monitor.add_observer(self)
...
def update
...
notify_observers(data, ...)
end

Module Singleton
class Klass
include Singleton
# ...
end
a, b = Klass.instance, Klass.instance
a == b # => true
a.new # raises NoMethodError

Other Third-party Libraries
Racc
See i.loveruby.net /en /man /racc
Test::Unit
assert(boolean, message=nil)
assert_block(message="assert_block failed.") do ... end
assert_equal(expected, actual, message=nil)
assert_in_delta(expected_float, actual_float, delta, message="")
assert_instance_of(klass, object, message="")
assert_kind_of(klass, object, message="")
assert_match(pattern, string, message="")
assert_nil(object, message="")
assert_no_match(regexp, string, message="")
assert_not_equal(expected, actual, message="")
assert_not_nil(object, message="")
assert_not_same(expected, actual, message="")
assert_nothing_raised(*args)
assert_nothing_thrown(message="") do ... end
assert_operator(object1, operator, object2, message="")
http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 13 of 14
Ruby QuickRef

11/29/2005 12:35 AM

assert_raises(expected_exception_klass, message="") do ... end
assert_respond_to(object, method, message="")
assert_same(expected, actual, message="")
assert_send(send_array, message="")
assert_throws(expected_symbol, message="") do ... end
flunk(message="Flunked")
Original URL: www.zenspider.com/Languages/Ruby/QuickRef.html
$Author: ryand $
$Date: 2005/11/01 $
$Revision: #34 $

Sitemap | Search || Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef
"More matter, with less art" - Gertrude, Hamlet.
Copyright © 1997-2004 Ryan Davis & Zen Spider Software. All Rights Reserved.
Generated: 2005-11-01 13:45:01

http://www.zenspider.com/Languages/Ruby/QuickRef.html

Page 14 of 14

Contenu connexe

Tendances (20)

PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
 
PHP Regular Expressions
PHP Regular ExpressionsPHP Regular Expressions
PHP Regular Expressions
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2
 
Grep - A powerful search utility
Grep - A powerful search utilityGrep - A powerful search utility
Grep - A powerful search utility
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Php
PhpPhp
Php
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Perl_Part4
Perl_Part4Perl_Part4
Perl_Part4
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 

En vedette (7)

Ruby
RubyRuby
Ruby
 
Ruby
RubyRuby
Ruby
 
Rubi
RubiRubi
Rubi
 
Ruby
RubyRuby
Ruby
 
Ruby
RubyRuby
Ruby
 
Ruby
RubyRuby
Ruby
 
Ruby
RubyRuby
Ruby
 

Similaire à Ruby quick ref

Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Roy Zimmer
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsRoy Zimmer
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmersamiable_indian
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variablesKing Hom
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptxNiladriDey18
 
Stop overusing regular expressions!
Stop overusing regular expressions!Stop overusing regular expressions!
Stop overusing regular expressions!Franklin Chen
 

Similaire à Ruby quick ref (20)

Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
ppt18
ppt18ppt18
ppt18
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmers
 
ppt9
ppt9ppt9
ppt9
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
Perl.predefined.variables
Perl.predefined.variablesPerl.predefined.variables
Perl.predefined.variables
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
Stop overusing regular expressions!
Stop overusing regular expressions!Stop overusing regular expressions!
Stop overusing regular expressions!
 

Dernier

Mookuthi is an artisanal nose ornament brand based in Madras.
Mookuthi is an artisanal nose ornament brand based in Madras.Mookuthi is an artisanal nose ornament brand based in Madras.
Mookuthi is an artisanal nose ornament brand based in Madras.Mookuthi
 
办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一
办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一
办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一F La
 
MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...
MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...
MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...katerynaivanenko1
 
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证nhjeo1gg
 
Cosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable BricksCosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable Bricksabhishekparmar618
 
How to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our SiteHow to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our Sitegalleryaagency
 
Call In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCR
Call In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCRCall In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCR
Call In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCRdollysharma2066
 
毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree 毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree ttt fff
 
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...Amil baba
 
Untitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptxUntitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptxmapanig881
 
Passbook project document_april_21__.pdf
Passbook project document_april_21__.pdfPassbook project document_april_21__.pdf
Passbook project document_april_21__.pdfvaibhavkanaujia
 
Architecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdfArchitecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdfSumit Lathwal
 
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书zdzoqco
 
CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10
CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10
CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10uasjlagroup
 
西北大学毕业证学位证成绩单-怎么样办伪造
西北大学毕业证学位证成绩单-怎么样办伪造西北大学毕业证学位证成绩单-怎么样办伪造
西北大学毕业证学位证成绩单-怎么样办伪造kbdhl05e
 
(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一
(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一
(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一Fi sss
 
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024CristobalHeraud
 
Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Rndexperts
 
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档208367051
 

Dernier (20)

Mookuthi is an artisanal nose ornament brand based in Madras.
Mookuthi is an artisanal nose ornament brand based in Madras.Mookuthi is an artisanal nose ornament brand based in Madras.
Mookuthi is an artisanal nose ornament brand based in Madras.
 
办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一
办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一
办理(宾州州立毕业证书)美国宾夕法尼亚州立大学毕业证成绩单原版一比一
 
MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...
MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...
MT. Marseille an Archipelago. Strategies for Integrating Residential Communit...
 
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
在线办理ohio毕业证俄亥俄大学毕业证成绩单留信学历认证
 
Call Girls in Pratap Nagar, 9953056974 Escort Service
Call Girls in Pratap Nagar,  9953056974 Escort ServiceCall Girls in Pratap Nagar,  9953056974 Escort Service
Call Girls in Pratap Nagar, 9953056974 Escort Service
 
Cosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable BricksCosumer Willingness to Pay for Sustainable Bricks
Cosumer Willingness to Pay for Sustainable Bricks
 
How to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our SiteHow to Be Famous in your Field just visit our Site
How to Be Famous in your Field just visit our Site
 
Call In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCR
Call In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCRCall In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCR
Call In girls Bhikaji Cama Place 🔝 ⇛8377877756 FULL Enjoy Delhi NCR
 
毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree 毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
毕业文凭制作#回国入职#diploma#degree澳洲弗林德斯大学毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#degree
 
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
NO1 Famous Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Add...
 
Untitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptxUntitled presedddddddddddddddddntation (1).pptx
Untitled presedddddddddddddddddntation (1).pptx
 
Passbook project document_april_21__.pdf
Passbook project document_april_21__.pdfPassbook project document_april_21__.pdf
Passbook project document_april_21__.pdf
 
Architecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdfArchitecture case study India Habitat Centre, Delhi.pdf
Architecture case study India Habitat Centre, Delhi.pdf
 
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
办理卡尔顿大学毕业证成绩单|购买加拿大文凭证书
 
CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10
CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10
CREATING A POSITIVE SCHOOL CULTURE CHAPTER 10
 
西北大学毕业证学位证成绩单-怎么样办伪造
西北大学毕业证学位证成绩单-怎么样办伪造西北大学毕业证学位证成绩单-怎么样办伪造
西北大学毕业证学位证成绩单-怎么样办伪造
 
(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一
(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一
(办理学位证)埃迪斯科文大学毕业证成绩单原版一比一
 
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
PORTFOLIO DE ARQUITECTURA CRISTOBAL HERAUD 2024
 
Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025Top 10 Modern Web Design Trends for 2025
Top 10 Modern Web Design Trends for 2025
 
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制堪培拉大学毕业证(UC毕业证)#文凭成绩单#真实留信学历认证永久存档
 

Ruby quick ref

  • 1. Ruby QuickRef 11/29/2005 12:35 AM Sitemap | Search || Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef Ruby QuickRef Contents: Contents Language General Syntax Rules Reserved words Types Numbers Strings Backslashes Here Docs Ranges Regexen Arrays Hashes Files Mode Strings Variables Pseudo variables Pre-defined variables Pre-defined global constants Expressions Terms Operators and Precedence Control Expressions Invoking a Method Defining a Class Defining a Module Defining a Method Access Restriction Accessors Aliasing Blocks, Closures, and Procs Blocks/Closures Proc Objects Exceptions, Catch, and Throw Standard Library Built-in Library Class Hierarchy Modules Standard Library Tools ruby Command Line Options Environment Variables irb xmp ruby-mode Debugger rdoc Mindshare, Idiom and Patterns Object Design Visitor Pattern Class SimpleDelegator, DelegateClass Module Observer http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 1 of 14
  • 2. Ruby QuickRef 11/29/2005 12:35 AM Module Singleton Other Third-party Libraries Racc Test::Unit Language General Syntax Rules Comments start with a pound/sharp (#) character and go to EOL. Ruby programs are sequence of expressions. Each expression is delimited by semicolons(;) or newlines unless obviously incomplete (e.g. trailing '+'). Backslashes at the end of line does not terminate expression. Reserved words alias do in return while and else module self yield BEGIN elsif next super begin END nil then break end not true case ensure or undef class false redo unless def for rescue until defined if retry when Types Basic types are numbers, strings, ranges, regexen, symbols, arrays, and hashes. Also included are files because they are used so often. Numbers 123 1_234 123.45 1.2e-3 0xffff (hex) 0b01011 (binary) 0377 (octal) ?a ASCII character ?C-a Control-a ?M-a Meta-a ?M-C-a Meta-Control-a :symbol Integer corresponding to identifiers, variables, and operators. Strings In all of the %() cases below, you may use any matching characters or any single character for delimiters. %[], %!!, %@@, etc. 'no interpolation' "#{interpolation}, and backslashesn" %q(no interpolation) %Q(interpolation and backslashes) %(interpolation and backslashes) `echo command interpretation with interpolation and backslashes` %x(echo command interpretation with interpolation and backslashes) Backslashes t (tab), n (newline), r (carriage return), f (form feed), b (backspace), a (bell), e (escape), s (whitespace), nnn (octal), xnn (hexadecimal), cx (control x), C-x (control x), M-x (meta x), M-C-x (meta control x) Here Docs <<identifier <<"identifier" <<'identifier' <<-identifier - interpolated, goes until identifier same thing no interpolation you can indent the identifier by using "-" in front Ranges 1..10 'a'..'z' (1..10) === 5 => true (1..10) === 15 => false while gets # prints lines starting at 'start' and ending at 'end' http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 2 of 14
  • 3. Ruby QuickRef 11/29/2005 12:35 AM while gets # prints lines starting at 'start' and ending at 'end' print if /start/../end/ end class RangeThingy # ... def <=>(rhs) # ... end def succ # ... end end range = RangeThingy.new(lower_bound)..RangeThingy.new(upper_bound) Regexen /normal regex/iomx[neus] %r|alternate form| options: /i /o /m /x /[neus] case insensitive case insensitive multiline mode - '.' will match newline extended mode - whitespace is ignored encoding: none, EUC, UTF-8, SJIS, respectively regex characters: . [ ] [^ ] * *? + +? ? | ( ) ^ $ #{m,n} #{m,n}? A b B b d D S s W w z Z (?# ) (?: ) (?= ) (?! ) (?ix-ix) (?ix-ix: ) any character except newline any single character of set any single character NOT of set 0 or more previous regular expression 0 or more previous regular expression(non greedy) 1 or more previous regular expression 1 or more previous regular expression(non greedy) 0 or 1 previous regular expression alternation grouping regular expressions beginning of a line or string end of a line or string at least m but most n previous regular expression at least m but most n previous regular expression(non greedy) beginning of a string backspace(0x08)(inside[]only) non-word boundary word boundary(outside[]only) digit, same as[0-9] non-digit non-whitespace character whitespace character[ tnrf] non-word character word character[0-9A-Za-z_] end of a string end of a string, or before newline at the end comment grouping without backreferences zero-width positive look-ahead assertion zero-width negative look-ahead assertion turns on/off i/x options, localized in group if any. turns on/off i/x options, localized in non-capturing group. Arrays [1, 2, 3] %w(foo bar baz) %W(foo bar baz #{var}) Indexes may be negative, and they index backwards (eg -1 is last element). http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 3 of 14
  • 4. Ruby QuickRef 11/29/2005 12:35 AM Hashes {1=>2, 2=>4, 3=>6} { expr => expr...} Files Common methods include: File.join(p1, p2, ... pN) => "p1/p2/.../pN" platform independent paths File.new(path, modestring="r") => file File.new(path, modenum [, permnum]) => file File.open(fileName, aModeString="r") {|file| block} -> nil File.open(fileName [, aModeNum [, aPermNum ]]) {|file| block} -> nil IO.foreach(path, sepstring=$/) {|line| block} IO.readlines(path) => array Mode Strings r Read-only, starts at beginning of file (default mode). r+ Read-write, starts at beginning of file. w Write-only, truncates existing file to zero length or creates a new file for writing. w+ Read-write, truncates existing file to zero length or creates a new file for reading and writing. a Write-only, starts at end of file if file exists, otherwise creates a new file for writing. a+ Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing. b (DOS/Windows only) Binary file mode (may appear with any of the key letters listed above). Variables $global_variable @instance_variable [OtherClass::]CONSTANT local_variable Pseudo variables self nil true false __FILE__ __LINE__ the the the the the the receiver of the current method sole instance of the Class NilClass(represents false) sole instance of the Class TrueClass(typical true value) sole instance of the Class FalseClass(represents false) current source file name. current line number in the source file. Pre-defined variables $! $@ $& $` $' $+ $1 $~ $= $/ $ $, $; $. $< The exception information message set by 'raise'. Array of backtrace of the last exception thrown. The string matched by the last successful pattern match in this scope. The string to the left of the last successful match. The string to the right of the last successful match. The last bracket matched by the last successful match. The Nth group of the last successful match. May be > 1. The information about the last match in the current scope. The flag for case insensitive, nil by default. The input record separator, newline by default. The output record separator for the print and IO#write. Default is nil. The output field separator for the print and Array#join. The default separator for String#split. The current input line number of the last file that was read. The virtual concatenation file of the files given on command line. http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 4 of 14
  • 5. Ruby QuickRef $> $_ $0 $* $$ $? $: $" $DEBUG $FILENAME $LOAD_PATH $stderr $stdin $stdout $VERBOSE $-0 $-a $-d $-F $-i $-I $-l $-p $-v 11/29/2005 12:35 AM The default output for print, printf. $stdout by default. The last input line of string by gets or readline. Contains the name of the script being executed. May be assignable. Command line arguments given for the script sans args. The process number of the Ruby running this script. The status of the last executed child process. Load path for scripts and binary modules by load or require. The array contains the module names loaded by require. The status of the -d switch. Current input file from $<. Same as $<.filename. The alias to the $:. The current standard error output. The current standard input. The current standard output. The verbose flag, which is set by the -v switch. The alias to $/. True if option -a is set. Read-only variable. The alias to $DEBUG. The alias to $;. In in-place-edit mode, this variable holds the extention, otherwise nil. The alias to $:. True if option -l is set. Read-only variable. True if option -p is set. Read-only variable. The alias to $VERBOSE. Pre-defined global constants TRUE FALSE NIL STDIN STDOUT STDERR ENV ARGF ARGV DATA RUBY_VERSION RUBY_RELEASE_DATE RUBY_PLATFORM The The The The The The The The The The The The The typical true value. false itself. nil itself. standard input. The default value for $stdin. standard output. The default value for $stdout. standard error output. The default value for $stderr. hash contains current environment variables. alias to the $<. alias to the $*. file object of the script, pointing just after __END__. ruby version string (VERSION was depricated). relase date string. platform identifier. Expressions Terms Terms are expressions that may be a basic type (listed above), a shell command, variable reference, constant reference, or method invocation. Operators and Precedence (Top to bottom) :: [] ** -(unary) +(unary) ! ~ * / % + << >> & | ^ > >= < <= <=> == === != =~ !~ && || .. ... =(+=, -=...) not and or All of the above are just methods except these: http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 5 of 14
  • 6. Ruby QuickRef 11/29/2005 12:35 AM =, .., ..., !, not, &&, and, ||, or, !=, !~ In addition, assignment operators(+= etc.) are not user-definable. Control Expressions if bool-expr [then] body elsif bool-expr [then] body else body end unless bool-expr [then] body else body end expr if bool-expr expr unless bool-expr case target-expr when comparison [, comparison]... [then] body when comparison [, comparison]... [then] body ... [else body] end (comparisons may be regexen) while bool-expr [do] body end until bool-expr [do] body end begin body end while bool-expr begin body end until bool-expr for name[, name]... in expr [do] body end expr.each do | name[, name]... | body end expr while bool-expr expr until bool-expr break terminates loop immediately. redo immediately repeats w/o rerunning the condition. next starts the next iteration through the loop. retry restarts the loop, rerunning the condition. Invoking a Method Nearly everything available in a method invocation is optional, consequently the syntax is very difficult to follow. Here are some examples: http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 6 of 14
  • 7. Ruby QuickRef 11/29/2005 12:35 AM method obj.method Class::method method(arg1, arg2) method(arg1, key1 => val1, key2 => val2, aval1, aval2) #{ block } method(arg1, *[arg2, arg3]) becomes: method(arg1, arg2, arg3) invocation := [receiver ('::' | '.')] name [ parameters ] [ block ] parameters := ( [param]* [, hashlist] [*array] [&aProc] ) block := { blockbody } | do blockbody end Defining a Class Classnames begin w/ capital character. class Identifier [< superclass ] expr.. end # singleton classes, add methods to a single instance class << obj expr.. end Defining a Module module Identifier expr.. end Defining a Method def method_name(arg_list, *list_expr, &block_expr) expr.. end # singleton method def expr.identifier(arg_list, *list_expr, &block_expr) expr.. end All items of the arg list, including parens, are optional. Arguments may have default values (name=expr). Method_name may be operators (see above). The method definitions can not be nested. Methods may override operators: .., |, ^, &, <=>, ==, ===, =~, >, >=, <, <=, +, -, *, /, %, **, <<, >>, ~, +@, -@, [], []= (2 args) Access Restriction public - totally accessable. protected - accessable only by instances of class and direct descendants. Even through hasA relationships. (see below) private - accessable only by instances of class. Restriction used w/o arguments set the default access control. Used with arguments, sets the access of the named methods and constants. class A protected def protected_method # nothing end end class B < A public def test_protected myA = A.new http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 7 of 14
  • 8. Ruby QuickRef 11/29/2005 12:35 AM myA.protected_method end end b = B.new.test_protected Accessors Class Module provides the following utility methods: attr_reader <attribute>[, <attribute>]... Creates a read-only accessor for each <attribute>. attr_writer <attribute>[, <attribute>]... Creates a write-only accessor for each <attribute>. attr <attribute> [, <writable>] Equivalent to "attr_reader <attribute>; attr_writer <attribute> if <writable>" attr_accessor <attribute>[, <attribute>]... Equivalent to "attr <attribute>, TRUE" for each argument. Aliasing alias :old :new alias_method :new, :old Creates a new reference to whatever old referred to. old can be any existing method, operator, global. It may not be a local, instance, constant, or class variable. Blocks, Closures, and Procs Blocks/Closures blocks must follow a method invocation: invocation do ... end invocation { ... } Blocks remember their variable context, and are full closures. Blocks are invoked via yield and may be passed arguments. Brace form has higher precidence and will bind to the last parameter if invocation made w/o parens. do/end form has lower precidence and will bind to the invocation even without parens. Proc Objects Created via: Kernel#proc Proc#new By invoking a method w/ a block argument. See class Proc for more information. Exceptions, Catch, and Throw Exception StandardError LocalJumpError SystemStackError ZeroDivisionError RangeError FloatDomainError SecurityError ThreadError IOError EOFError ArgumentError IndexError http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 8 of 14
  • 9. Ruby QuickRef 11/29/2005 12:35 AM RuntimeError TypeError SystemCallError Errno::* RegexpError SignalException Interrupt fatal NoMemoryError ScriptError LoadError NameError SyntaxError NotImplementedError SystemExit begin expr.. [rescue [error_type [=> var],..] expr..].. [else expr..] [ensure expr..] end The default error_type for resuce is StandardError, not Exception. Standard Library Ruby comes with an extensive library of classes and modules. Some are built-in, and some are part of the standard library. You can distinguish the two by the fact that the built-in classes are in fact, built-in. There are no dot-rb files for them. Built-in Library Class Hierarchy Object Hash Symbol IO File Continuation File::Stat Data NilClass Exception (see tree above) Array Proc String Numeric Float Integer Bignum Fixnum Regexp Thread Module Class ThreadGroup Method UnboundMethod http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 9 of 14
  • 10. Ruby QuickRef 11/29/2005 12:35 AM Struct Struct::Tms TrueClass Time Dir Binding Range MatchData FalseClass Modules Comparable Enumerable Errno FileTest GC Kernel Marshal Math ObjectSpace Precision Process Standard Library The essentials: benchmark.rb a simple benchmarking utility cgi-lib.rb decode CGI data - simpler than cgi.rb cgi.rb CGI interaction date.rb date object (compatible) debug.rb ruby debugger delegate.rb delegate messages to other object English.rb access global variables by english names fileutils.rb file utility methods for copying, moving, removing, etc. find.rb traverse directory tree jcode.rb UTF-8 and Japanese String helpers (replaces String methods) net/*.rb Networking classes of all kinds observer.rb observer desing pattern library (provides Observable) open-uri.rb good wrapper for net/http, net/https and net/ftp open3.rb open subprocess connection stdin/stdout/stderr ostruct.rb python style object (freeform assignment to instance vars) parsearg.rb argument parser using getopts pp prettier debugging output, 'p' on steroids. profile.rb ruby profiler - find that slow code! pstore.rb persistent object strage using marshal rexml/*.rb XML toolkit singleton.rb singleton design pattern library stringio lets you use an IO attached to a string. tempfile.rb temporary file that automatically removed test/unit unit testing framework time.rb extension to Time class with a lot of converters tracer.rb execution tracer webrick Fairly spiffy web server yaml alternative readable serialization format Tools ruby Command Line Options http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 10 of 14
  • 11. Ruby QuickRef -0[octal] -a -c -Cdirectory --copyright -d -e 'command' -F regexp -h -i[extension] -Idirectory -Kkcode -l -n -p -rlibrary -s -S -T[level] -v --version -w -x[directory] -X directory -y 11/29/2005 12:35 AM specify record separator (0, if no argument). autosplit mode with -n or -p (splits $_ into $F). check syntax only. cd to directory, before executing your script. print the copyright and exit. set debugging flags (set $DEBUG to true). one line of script. Several -e's allowed. split() pattern for autosplit (-a). prints summary of the options. edit ARGV files in place (make backup if extension supplied). specify $LOAD_PATH directory (may be used more than once). specifies KANJI (Japanese) code-set. enable line ending processing. assume 'while gets(); ... end' loop around your script. assume loop like -n but print line also like sed. require the library, before executing your script. enable some switch parsing for switches after script name. look for the script using PATH environment variable. turn on tainting checks. print version number, then turn on verbose mode. print the version and exit. turn warnings on for your script. strip off text before #! line and perhaps cd to directory. causes Ruby to switch to the directory. turns on compiler debug mode. Environment Variables DLN_LIBRARY_PATH RUBYLIB RUBYLIB_PREFIX RUBYOPT RUBYPATH RUBYSHELL Search path for dynamically loaded modules. Additional search paths. Add this prefix to each item in RUBYLIB. Windows only. Additional command line options. With -S, searches PATH, or this value for ruby programs. Shell to use when spawning. irb irb [options] [script [args]] The essential options are: -d -f -h -m -r module -v --inf-ruby-mode --inspect --noinspect --noprompt --noreadline --prompt --readline --tracer Sets $DEBUG to true. Same as "ruby -d ..." Prevents the loading of ~/.irb.rc. Get a full list of options. Math mode. Overrides --inspect. Loads "mathn.rb". Loads a module. Same as "ruby -r module ..." Prints the version and exits. Turns on emacs support and turns off readline. Turns on inspect mode. Default. Turns off inspect mode. Turns off the prompt. Turns off readline support. Sets to one of 'default', 'xmp', 'simple', or 'inf-ruby'. Turns on readline support. Default. Turns on trace mode. Besides arbitrary ruby commands, the special commands are: exit fork block cb args source file irb [obj] conf[.key[= val]] jobs fg session kill session exits the current session, or the program forks and runs the given block changes to a secified binding loads a ruby file into the session starts a new session, with obj as self, if specified access the configuration of the session lists the known sessions switches to the specifed session kills a specified session Session may be specified via session#, thread-id, obj, or self. http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 11 of 14
  • 12. Ruby QuickRef 11/29/2005 12:35 AM xmp require "irb/xmp" xmp "something to eval" # or: x = XMP.new x.puts "something to eval" ruby-mode TODO: I don't have a freakin clue how to use the inferior ruby thing... I always fire up a shell in emacs... DOH! Debugger To invoke the debugger: ruby -r debug ... To use the debugger: b[reak] [file:|class:]<line|method b[reak] [class.]<line|method set breakpoint to some position wat[ch] expression set watchpoint to some expression cat[ch] exception set catchpoint to an exception b[reak] list breakpoints cat[ch] show catchpoint del[ete][ nnn] delete some or all breakpoints disp[lay] expression add expression into display expression list undisp[lay][ nnn] delete one particular or all display expressions c[ont] run until program ends or hit breakpoint s[tep][ nnn] step (into methods) one line or till line nnn n[ext][ nnn] go over one line or till line nnn w[here] display frames f[rame] alias for where l[ist][ (-|nn-mm)] list program, - lists backwards nn-mm lists given lines up[ nn] move to higher frame down[ nn] move to lower frame fin[ish] return to outer frame tr[ace] (on|off) set trace mode of current thread tr[ace] (on|off) all set trace mode of all threads q[uit] exit from debugger v[ar] g[lobal] show global variables v[ar] l[ocal] show local variables v[ar] i[nstance] object show instance variables of object v[ar] c[onst] object show constants of object m[ethod] i[nstance] obj show methods of object m[ethod] class|module show instance methods of class or module th[read] l[ist] list all threads th[read] c[ur[rent]] show current thread th[read] [sw[itch]] nnn switch thread context to nnn th[read] stop nnn stop thread nnn th[read] resume nnn resume thread nnn p expression evaluate expression and print its value h[elp] print this help everything else evaluate empty repeats the last command rdoc =begin the everything between a line beginning with `=begin' and that with `=end' will be skipped by the interpreter. =end FIX: there is a lot more to rdoc. Mindshare, Idiom and Patterns http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 12 of 14
  • 13. Ruby QuickRef 11/29/2005 12:35 AM Object Design Visitor Pattern By defining the method #each and including Enumerable, you get to use all the methods in Enumerable: class Mailbox include Enumerable # ... def each @mail.each do # ... yield end end end Class SimpleDelegator, DelegateClass foo = Object.new foo2 = SimpleDelegator.new(foo) foo.hash == foo2.hash # => false Foo = DelegateClass(Array) class ExtArray<DelegateClass(Array) ... end Module Observer monitor.add_observer(self) ... def update ... notify_observers(data, ...) end Module Singleton class Klass include Singleton # ... end a, b = Klass.instance, Klass.instance a == b # => true a.new # raises NoMethodError Other Third-party Libraries Racc See i.loveruby.net /en /man /racc Test::Unit assert(boolean, message=nil) assert_block(message="assert_block failed.") do ... end assert_equal(expected, actual, message=nil) assert_in_delta(expected_float, actual_float, delta, message="") assert_instance_of(klass, object, message="") assert_kind_of(klass, object, message="") assert_match(pattern, string, message="") assert_nil(object, message="") assert_no_match(regexp, string, message="") assert_not_equal(expected, actual, message="") assert_not_nil(object, message="") assert_not_same(expected, actual, message="") assert_nothing_raised(*args) assert_nothing_thrown(message="") do ... end assert_operator(object1, operator, object2, message="") http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 13 of 14
  • 14. Ruby QuickRef 11/29/2005 12:35 AM assert_raises(expected_exception_klass, message="") do ... end assert_respond_to(object, method, message="") assert_same(expected, actual, message="") assert_send(send_array, message="") assert_throws(expected_symbol, message="") do ... end flunk(message="Flunked") Original URL: www.zenspider.com/Languages/Ruby/QuickRef.html $Author: ryand $ $Date: 2005/11/01 $ $Revision: #34 $ Sitemap | Search || Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef "More matter, with less art" - Gertrude, Hamlet. Copyright © 1997-2004 Ryan Davis & Zen Spider Software. All Rights Reserved. Generated: 2005-11-01 13:45:01 http://www.zenspider.com/Languages/Ruby/QuickRef.html Page 14 of 14