Ruby QuickRef

来源:百度文库 编辑:神马文学网 时间:2024/04/25 03:19:13
Sitemap |Search ||Zen Spider Website /The Language Freak /Ruby / Ruby QuickRef
Ruby QuickRef
ContentsLanguageGeneral Syntax RulesReserved wordsTypesNumbersStringsBackslashesHere Docs
SymbolsRangesRegexenArraysHashesFilesMode Strings
VariablesPseudo variablesPre-defined variablesPre-defined global constantsExpressionsTermsOperators and PrecedenceControl Expressions
Invoking a MethodDefining a ClassDefining a ModuleDefining a MethodAccess RestrictionAccessors
AliasingBlocks, Closures, and ProcsBlocks/ClosuresProc Objects
Exceptions, Catch, and Throw
Standard LibraryBuilt-in LibraryClass HierarchyModules
Standard Library
ToolsrubyCommand Line OptionsEnvironment Variables
irbxmpruby-modeDebuggerrdoc
Mindshare, Idiom and PatternsObject DesignVisitor PatternClass SimpleDelegator, DelegateClassModule ObserverModule Singleton
Other Third-party LibrariesRaccTest::Unit
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.
alias and BEGIN begin break case class def defineddo else elsif END end ensure false for ifin module next nil not or redo rescue retryreturn self super then true undef unless until whenwhile yield
Basic types are numbers, strings, ranges, regexen, symbols, arrays, and hashes. Also included are files because they are used so often.
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
In all of the %() cases below, you may use any matching characters or any single character for delimiters. %[], %!!, %@@, etc.
‘no interpolation‘"#{interpolation}, and backslashes\n"%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)
\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)
<Internalized String. Guaranteed to be unique and quickly comparable. Ideal for hash keys. Symbols may not contain \0 or be empty.
:symbol => :symbol:‘#{"without"} interpolation‘ => :"#{"without"} interpolation":"#{"with"} interpolation" => :"with interpolation"%s(#{"without"} interpolation) => :"#{"without"} interpolation"
1..101...10‘a‘..‘z‘‘a‘...‘z‘(1..10) === 5 => true(1..10) === 10 => true(1...10) === 10 => false(1..10) === 15 => falsewhile gets # prints lines starting at ‘start‘ and ending at ‘end‘print if /start/../end/endclass comparable# ...def <=>(rhs)# ...enddef succ# ...endendrange = RangeThingy.new(lower_bound)..RangeThingy.new(upper_bound)
/normal regex/iomx[neus]%r|alternate form|
options:
/i case insensitive/o only interpolate #{} blocks once/m multiline mode - ‘.‘ will match newline/x extended mode - whitespace is ignored/[neus] encoding: none, EUC, UTF-8, SJIS, respectively
regex characters:
. 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{m,n} at least m but most n previous regular expression{m,n}? at least m but most n previous regular expression(non greedy)\A beginning of a string\b backspace(0x08)(inside[]only)\B non-word boundary\b word boundary(outside[]only)\d digit, same as[0-9]\D non-digit\S non-whitespace character\s whitespace character[ \t\n\r\f]\W non-word character\w word character[0-9A-Za-z_]\z end of a string\Z 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(?ix-ix) turns on/off i/x options, localized in group if any.(?ix-ix: ) turns on/off i/x options, localized in non-capturing group.
[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).
{1=>2, 2=>4, 3=>6}{ expr => expr...}
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
rRead-only, starts at beginning of file (default mode).r+Read-write, starts at beginning of file.wWrite-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.aWrite-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).
$global_variable@@class_variable@instance_variable[OtherClass::]CONSTANTlocal_variable
self the receiver of the current methodnil the sole instance of the Class NilClass(represents false)true the sole instance of the Class TrueClass(typical true value)false the sole instance of the Class FalseClass(represents false)__FILE__ the current source file name.__LINE__ the current line number in the source file.
$! 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.$1 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.$> The default output for print, printf. $stdout by default.$_ The last input line of string by gets or readline.$0 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.$DEBUG The status of the -d switch.$FILENAME Current input file from $<. Same as $<.filename.$LOAD_PATH The alias to the $:.$stderr The current standard error output.$stdin The current standard input.$stdout The current standard output.$VERBOSE The verbose flag, which is set by the -v switch.$-0 The alias to $/.$-a True if option -a is set. Read-only variable.$-d The alias to $DEBUG.$-F The alias to $;.$-i In in-place-edit mode, this variable holds the extension, otherwise nil.$-I The alias to $:.$-l True if option -l is set. Read-only variable.$-p True if option -p is set. Read-only variable.$-v The alias to $VERBOSE.$-w True if option -w is set.
TRUE The typical true value.FALSE The false itself.NIL The nil itself.STDIN The standard input. The default value for $stdin.STDOUT The standard output. The default value for $stdout.STDERR The standard error output. The default value for $stderr.ENV The hash contains current environment variables.ARGF The alias to the $<.ARGV The alias to the $*.DATA The file object of the script, pointing just after __END__.RUBY_VERSION The ruby version string (VERSION was deprecated).RUBY_RELEASE_DATE The release date string.RUBY_PLATFORM The platform identifier.
Terms are expressions that may be a basic type (listed above), a shell command, variable reference, constant reference, or method invocation.
(Top to bottom):: .[]**-(unary) +(unary) ! ~* / %+ -<< >>&| ^> >= < <=<=> == === != =~ !~&&||.. ...=(+=, -=...)notand or
All of the above are just methods except these:
=, ::, ., .., ..., !, not, &&, and, ||, or, !=, !~
In addition, assignment operators(+= etc.) are not user-definable.
if bool-expr [then]bodyelsif bool-expr [then]bodyelsebodyendunless bool-expr [then]bodyelsebodyendexpr if bool-exprexpr unless bool-exprcase target-exprwhen comparison [, comparison]... [then]bodywhen comparison [, comparison]... [then]body...[elsebody]end
(comparisons may be regexen)
loop dobodyendwhile bool-expr [do]bodyenduntil bool-expr [do]bodyendbeginbodyend while bool-exprbeginbodyend until bool-exprfor name[, name]... in expr [do]bodyendexpr.each do | name[, name]... |bodyendexpr while bool-exprexpr 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.
Nearly everything available in a method invocation is optional, consequently the syntax is very difficult to follow. Here are some examples:
method obj.method Class::method method(key1 => val1, key2 => val2) is one argument for def method(hash_arg) !
method(arg1, *[arg2, arg3]) becomes: method(arg1, arg2, arg3) as ugly as you want it to be: method(arg1, key1 => val1, key2 => val2, *splat_arg) #{ block }
invocation := [receiver (‘::‘ | ‘.‘)] name [ parameters ] [ block ]parameters := ( [param]* [, hashlist] [*array] [&aProc] )block := { blockbody } | do blockbody end
Class names begin w/ capital character.
class Identifier [< superclass ]expr..end# singleton classes, add methods to a single instanceclass << objexpr..end
module Identifierexpr..end
def method_name(arg_list, *list_expr, &block_expr)expr..end# singleton methoddef 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)
public - totally accessible. protected - accessible only by instances of class and direct descendants. Even through hasA relationships. (see below) private - accessible only by instances of class (must be called nekkid no "self." or anything else).
Restriction used w/o arguments set the default access control. Used with arguments, sets the access of the named methods and constants.
class Aprotecteddef protected_method# nothingendendclass B < Apublicdef test_protectedmyA = A.newmyA.protected_methodendendb = B.new.test_protected
Class Module provides the following utility methods:
attr_reader [, ]...Creates a read-only accessor for each .attr_writer [, ]...Creates a write-only accessor for each .attr [, ]Equivalent to "attr_reader ; attr_writer if "attr_accessor [, ]...Equivalent to "attr , TRUE" for each argument.
alias :new :oldalias_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 must follow a method invocation:
invocation do ... endinvocation { ... } Blocks remember their variable context, and are full closures. Blocks are invoked via yield and may be passed arguments. Brace form has higher precedence and will bind to the last parameter if invocation made w/o parens. do/end form has lower precedence and will bind to the invocation even without parens.
Created via:
Kernel#proc Proc#new By invoking a method w/ a block argument.
See class Proc for more information.
Exception NoMemoryError ScriptError LoadError NotImplementedError SyntaxError
SignalException Interrupt
StandardError (default for rescue) ArgumentError IOError EOFError
IndexError LocalJumpError NameError NoMethodError
RangeError FloatDomainError
RegexpError RuntimeError (default for rai