RubyCheatSheet

From $1

Table of contents
[MISSING]

<UL>

  • <LI><A HREF="#1">Language</A></LI> <UL>

    • <LI><A HREF="#2">General Syntax Rules</A></LI> <LI><A HREF="#3">Reserved words</A></LI> <LI><A HREF="#4">Types</A></LI> <UL>

      • <LI><A HREF="#5">Numbers</A></LI> <LI><A HREF="#6">Strings</A></LI> <UL>

        • <LI><A HREF="#7">Backslashes</A></LI> <LI><A HREF="#8">Here Docs</A></LI>

        </UL> <LI><A HREF="#9">Ranges</A></LI> <LI><A HREF="#10">Regexen</A></LI> <LI><A HREF="#11">Arrays</A></LI> <LI><A HREF="#12">Hashes</A></LI> <LI><A HREF="#13">Files</A></LI> <UL>

        • <LI><A HREF="#14">Mode Strings</A></LI>

        </UL>

      </UL> <LI><A HREF="#15">Variables</A></LI> <LI><A HREF="#16">Pseudo variables</A></LI> <LI><A HREF="#17">Pre-defined variables</A></LI> <LI><A HREF="#18">Pre-defined global constants</A></LI> <LI><A HREF="#19">Expressions</A></LI> <UL>

      • <LI><A HREF="#20">Terms</A></LI> <LI><A HREF="#21">Operators and Precedence</A></LI> <LI><A HREF="#22">Control Expressions</A></LI>

      </UL> <LI><A HREF="#23">Invoking a Method</A></LI> <LI><A HREF="#24">Defining a Class</A></LI> <LI><A HREF="#25">Defining a Module</A></LI> <LI><A HREF="#26">Defining a Method</A></LI> <UL>

      • <LI><A HREF="#27">Access Restriction</A></LI> <LI><A HREF="#28">Accessors</A></LI>

      </UL> <LI><A HREF="#29">Aliasing</A></LI> <LI><A HREF="#30">Blocks, Closures, and Procs</A></LI> <UL>

      • <LI><A HREF="#31">Blocks/Closures</A></LI> <LI><A HREF="#32">Proc Objects</A></LI>

      </UL> <LI><A HREF="#33">Exceptions, Catch, and Throw</A></LI>

    </UL> <LI><A HREF="#34">Standard Library</A></LI> <UL>

    • <LI><A HREF="#35">Built-in Library</A></LI> <UL>

      • <LI><A HREF="#36">Class Hierarchy</A></LI> <LI><A HREF="#37">Modules</A></LI>

      </UL> <LI><A HREF="#38">Standard Library</A></LI> <UL>

      • <LI><A HREF="#39">Classes</A></LI> <LI><A HREF="#40">Modules</A></LI> <LI><A HREF="#41">Mixins</A></LI> <LI><A HREF="#42">Socket</A></LI> <LI><A HREF="#43">Net:</A></LI> <LI><A HREF="#44">CGI:</A></LI> <LI><A HREF="#45">MS</A></LI>

      </UL>

    </UL> <LI><A HREF="#46">Tools</A></LI> <UL>

    • <LI><A HREF="#47">ruby</A></LI> <UL>

      • <LI><A HREF="#48">Command Line Options</A></LI> <LI><A HREF="#49">Environment Variables</A></LI>

      </UL> <LI><A HREF="#50">irb</A></LI> <LI><A HREF="#51">rtags</A></LI> <LI><A HREF="#52">xmp</A></LI> <LI><A HREF="#53">ruby-mode</A></LI> <LI><A HREF="#54">Debugger</A></LI> <LI><A HREF="#55">old: Embedded Documentation</A></LI>

    </UL> <LI><A HREF="#56">Mindshare, Idiom and Patterns</A></LI> <UL>

    • <LI><A HREF="#57">Object Design</A></LI> <LI><A HREF="#58">Other Third-party Libraries</A></LI> <UL>

      • <LI><A HREF="#59">Amstd</A></LI> <LI><A HREF="#60">Racc</A></LI> <LI><A HREF="#61">Optparse</A></LI> <LI><A HREF="#62">Test::Unit</A></LI>

      </UL>

    </UL>

</UL> <H2><A NAME="1">Language</A></H2>

<H3><A NAME="2">General Syntax Rules</A></H3>

<UL>

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

</UL> <H3><A NAME="3">Reserved words</A></H3>

<PRE>alias and BEGIN begin break case class def defined do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield </PRE>

<H3><A NAME="4">Types</A></H3>

<P>Basic types are numbers, strings, ranges, regexen, symbols, arrays, and hashes. Also included are files because they are used so often.</P>

<H4><A NAME="5">Numbers</A></H4>

<PRE>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.</PRE>

<H4><A NAME="6">Strings</A></H4>

<PRE>'no interpolation' "#{interpolation}, #{$interpolation}, #{@interpolation}, and backslashes\n" %q!no interpolation! %!interpolation and backslashes! %Q(interpolation and backslashes) echo command interpretation with interpolation and backslashes %x/echo command interpretation with interpolation and backslashes/</PRE>

<H5><A NAME="7">Backslashes</A></H5>

<PRE>\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)</PRE>

<H5><A NAME="8">Here Docs</A></H5>

<PRE><<identifier, <<"identifier", <<-identifier</PRE>

<H4><A NAME="9">Ranges</A></H4>

<PRE>1..10 'a'..'z' (1..10) === 5 => true (1..10) === 15 => false

while gets # prints lines starting at 'start' and ending at 'end'

  • print if /start/../end/

end</PRE>

<PRE>class RangeThingy

  • # ...

    def <=>(rhs)

    • # ...
    end def succ
    • # ...
    end

end range = RangeThingy.new(lower_bound)..RangeThingy.new(upper_bound)</PRE>

<H4><A NAME="10">Regexen</A></H4>

<PRE>/normal regex/i %r|alternate form|</PRE>

<PRE>. 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.</PRE>

<H4><A NAME="11">Arrays</A></H4>

<PRE>[1, 2, 3] %w(foo bar baz)</PRE>

<P>Indexes may be negative, and they index backwards (eg -1 is last element).</P>

<H4><A NAME="12">Hashes</A></H4>

<PRE>{1=>2, 2=>4, 3=>6} { expr => expr...}</PRE>

<H4><A NAME="13">Files</A></H4>

<P>Common methods include:</P>

<UL>

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

</UL> <H5><A NAME="14">Mode Strings</A></H5>

<DL>

  • <DT>r</DT> <DD>Read-only, starts at beginning of file (default mode).</DD>

    <DT>r+</DT> <DD>Read-write, starts at beginning of file.</DD>

    <DT>w</DT> <DD>Write-only, truncates existing file to zero length or creates a new file for writing.</DD>

    <DT>w+</DT> <DD>Read-write, truncates existing file to zero length or creates a new file for reading and writing.</DD>

    <DT>a</DT> <DD>Write-only, starts at end of file if file exists, otherwise creates a new file for writing.</DD>

    <DT>a+</DT> <DD>Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.</DD>

    <DT>b</DT> <DD>(DOS/Windows only) Binary file mode (may appear with any of the key letters listed above).</DD>

</DL>

<H3><A NAME="15">Variables</A></H3>

<PRE>$global_variable @instance_variable [OtherClass::]CONSTANT local_variable</PRE>

<H3><A NAME="16">Pseudo variables</A></H3>

<PRE>self the receiver of the current method nil 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.</PRE>

<H3><A NAME="17">Pre-defined variables</A></H3>

<PRE>$! 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 extention, 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.</PRE>

<H3><A NAME="18">Pre-defined global constants</A></H3>

<PRE>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. VERSION The Ruby version string. RUBY_RELEASE_DATE The relase date string. RUBY_PLATFORM The platform identifier.</PRE>

<H3><A NAME="19">Expressions</A></H3>

<H4><A NAME="20">Terms</A></H4>

<P>Terms are expressions that may be a basic type (listed above), a shell command, variable reference, constant reference, or method invocation.</P>

<H4><A NAME="21">Operators and Precedence</A></H4>

<PRE>(Top to bottom) :: [] ** -(unary) +(unary) ! ~ * / % + - << >> & | ^ > >= < <= <=> == === != =~ !~ && || .. ... =(+=, -=...) not and or</PRE>

<P>All of the above are just methods except these:</P>

<PRE>=, .., ..., !, not, &&, and, ||, or, !=, !~</PRE>

<P>In addition, assignment operators(+= etc.) are not user-definable.</P>

<H4><A NAME="22">Control Expressions</A></H4>

<PRE>if bool-expr [then]

  • body

elsif bool-expr [then]

  • body

else

  • body

end</PRE>

<PRE>unless bool-expr [then]

  • body

else

  • body

end</PRE>

<PRE>expr if bool-expr expr unless bool-expr</PRE>

<PRE>case target-expr

  • when comparison [, comparison]... [then]
    • body
    when comparison [, comparison]... [then]
    • body
  • ..

[else

  • body]

end</PRE>

<P>(comparisons may be regexen)</P>

<PRE>while bool-expr [do]

  • body

end</PRE>

<PRE>until bool-expr [do]

  • body

end</PRE>

<PRE>begin

  • body

end while bool-expr</PRE>

<PRE>begin

  • body

end until bool-expr</PRE>

<PRE>for name[, name]... in expr [do]

  • body

end</PRE>

<PRE>expr.each do | name[, name]... |

  • body

end</PRE>

<PRE>expr while bool-expr expr until bool-expr</PRE>

<UL>

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

</UL> <H3><A NAME="23">Invoking a Method</A></H3>

<P>Nearly everything available in a method invocation is optional, consequently the syntax is very difficult to follow. Here are some examples:</P>

<UL>

  • <LI>method</LI> <LI>obj.method</LI> <LI>Class::method</LI> <LI>method(arg1, arg2)</LI> <LI>method(arg1, key1 => val1, key2 => val2, aval1, aval2) #{ block }</LI> <LI>method(arg1, *[arg2, arg3]) becomes: method(arg1, arg2, arg3)</LI>

</UL> <PRE>invocation := [receiver ('::' | '.')] name [ parameters ] [ block ] parameters := ( [param]* [, hashlist] [*array] [&aProc] ) block := { blockbody } | do blockbody end </PRE>

<H3><A NAME="24">Defining a Class</A></H3>

<P>Classnames begin w/ capital character.</P>

<PRE>class Identifier [< superclass ]

  • expr..

end</PRE>

<PRE># singleton classes, add methods to a single instance class << obj

  • expr..

end</PRE>

<H3><A NAME="25">Defining a Module</A></H3>

<PRE>module Identifier

  • expr..

end</PRE>

<H3><A NAME="26">Defining a Method</A></H3>

<PRE>def method_name(arg_list, *list_expr, &block_expr)

  • expr..

end</PRE>

<PRE># singleton method def expr.identifier(arg_list, *list_expr, &block_expr)

  • expr..

end</PRE>

<UL>

  • <LI>All items of the arg list, including parens, are optional.</LI> <LI>Arguments may have default values (name=expr).</LI> <LI>Method_name may be operators (see above).</LI> <LI>The method definitions can not be nested.</LI> <LI>Methods may override operators: .., |, ^, &, <=>, ==, ===, =~, >, >=, <, <=, +, -, *, /, %, **, <<, >>, ~, +@, -@, [], []= (2 args)</LI>

</UL> <H4><A NAME="27">Access Restriction</A></H4>

<UL>

  • <LI>public - totally accessable.</LI> <LI>protected - accessable only by instances of class and direct descendants. Even through hasA relationships. (see below)</LI> <LI>private - accessable only by instances of class.</LI>

</UL> <UL>

  • <LI>Restriction used w/o arguments set the default access control.</LI> <LI>Used with arguments, sets the access of the named methods and constants.</LI>

</UL> <PRE>class A

  • protected def protected_method
    • # nothing
    end

end class B < A

  • public def test_protected
    • myA = A.new myA.protected_method
    end

end b = B.new.test_protected</PRE>

<H4><A NAME="28">Accessors</A></H4>

<P>Class Module provides the following utility methods:</P>

<DL>

  • <DT>attr_reader <attribute>[, <attribute>]...</DT> <DD>Creates a read-only accessor for each <attribute>.</DD>

    <DT>attr_writer <attribute>[, <attribute>]...</DT> <DD>Creates a write-only accessor for each <attribute>.</DD>

    <DT>attr <attribute> [, <writable>]</DT> <DD>Equivalent to "attr_reader <attribute>; attr_writer <attribute> if <writable>"</DD>

    <DT>attr_accessor <attribute>[, <attribute>]...</DT> <DD>Equivalent to "attr <attribute>, TRUE" for each argument.</DD>

</DL>

<H3><A NAME="29">Aliasing</A></H3>

<PRE>alias <old> <new></PRE>

<P>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.</P>

<H3><A NAME="30">Blocks, Closures, and Procs</A></H3>

<H4><A NAME="31">Blocks/Closures</A></H4>

<UL>

  • <LI>blocks must follow a method invocation:</LI>

</UL> <PRE>invocation do ... end invocation { ... }</PRE>

<UL>

  • <LI>Blocks remember their variable context, and are full closures.</LI> <LI>Blocks are invoked via yield and may be passed arguments.</LI> <LI>Brace form has higher precidence and will bind to the last parameter if invocation made w/o parens.</LI> <LI>do/end form has lower precidence and will bind to the invocation even without parens.</LI>

</UL> <H4><A NAME="32">Proc Objects</A></H4>

<P>Created via:</P>

<UL>

  • <LI>Kernel#proc</LI> <LI>Proc#new</LI> <LI>By invoking a method w/ a block argument.</LI>

</UL> <P>See class Proc for more information.</P>

<H3><A NAME="33">Exceptions, Catch, and Throw</A></H3>

<UL>

</UL> <PRE>begin

  • expr..

[rescue [error_type [=> var],..]

  • expr..]..

[else

  • expr..]

[ensure

  • expr..]

end</PRE>

<P>The default error_type for resuce is StandardError, not Exception.</P>

<H2><A NAME="34">Standard Library</A></H2>

<P>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.</P>

<H3><A NAME="35">Built-in Library</A></H3>

<H4><A NAME="36">Class Hierarchy</A></H4>

<UL>

</UL> <H4><A NAME="37">Modules</A></H4>

<UL>

  • <LI>Comparable</LI> <LI>Enumerable</LI> <LI>Errno</LI> <LI>FileTest</LI> <LI>GC</LI> <LI>Kernel</LI> <LI>Marshal</LI> <LI>Math</LI> <LI>ObjectSpace</LI> <LI>Precision</LI> <LI>Process</LI>

</UL> <H3><A NAME="38">Standard Library</A></H3>

<UL>

  • <LI>base64.rb encode/decode base64 (obsolete)</LI> <LI>cgi-lib.rb decode CGI data</LI> <LI>cgi.rb</LI> <LI>cgi/session.rb</LI> <LI>complex.rb complex number suppor</LI> <LI>date.rb date object (compatible)</LI> <LI>debug.rb ruby debugger</LI> <LI>delegate.rb delegate messages to other object</LI> <LI>e2mmap.rb exception utilities</LI> <LI>English.rb access global variables by english names</LI> <LI>Env.rb access environment variables as globals</LI> <LI>eregex.rb extended regular expression (just a proof of concept)</LI> <LI>expect.rb</LI> <LI>final.rb add finalizer to the object (simple)</LI> <LI>finalize.rb add finalizer to the object</LI> <LI>find.rb traverse directory tree</LI> <LI>ftools.rb file tools</LI> <LI>ftplib.rb ftp access library</LI> <LI>getoptlong.rb GNU getoptlong compatible</LI> <LI>getopts.rb parse command line options</LI> <LI>i386-freebsd4.2/rbconfig.rb</LI> <LI>importenv.rb access environment variables as globals</LI> <LI>irb/completion.rb</LI> <LI>irb/frame.rb</LI> <LI>irb/input-method.rb</LI> <LI>irb/irb.rb</LI> <LI>irb/loader.rb</LI> <LI>irb/main.rb</LI> <LI>irb/multi-irb.rb</LI> <LI>irb/ruby-lex.rb</LI> <LI>irb/ruby-token.rb</LI> <LI>irb/slex.rb</LI> <LI>irb/version.rb</LI> <LI>irb/workspace-binding-2.rb</LI> <LI>irb/workspace-binding.rb</LI> <LI>irb/xmp.rb</LI> <LI>jcode.rb japanese text handling (replace String methods)</LI> <LI>kconv.rb</LI> <LI>mailread.rb read mail headers</LI> <LI>mathn.rb extended math operation</LI> <LI>matrix.rb matrix calculation library</LI> <LI>mkmf.rb Makefile maker</LI> <LI>monitor.rb exclusive region monitor for thread</LI> <LI>mutex_m.rb mutex mixin</LI> <LI>net/ftp.rb</LI> <LI>net/http.rb</LI> <LI>net/imap.rb</LI> <LI>net/pop.rb</LI> <LI>net/protocol.rb</LI> <LI>net/smtp.rb</LI> <LI>net/telnet.rb</LI> <LI>observer.rb observer desing pattern library (provides Observable)</LI> <LI>open3.rb open subprocess connection stdin/stdout/stderr</LI> <LI>ostruct.rb python style object</LI> <LI>parsearg.rb argument parser using getopts</LI> <LI>parsedate.rb parse date string</LI> <LI>ping.rb check whether host is up, using TCP echo.</LI> <LI>profile.rb ruby profiler</LI> <LI>pstore.rb persistent object strage using marshal</LI> <LI>rational.rb rational number support</LI> <LI>readbytes.rb define IO#readbytes</LI> <LI>shell.rb shell like operation under Ruby (imcomplete)</LI> <LI>shellwords.rb split into words like shell</LI> <LI>singleton.rb singleton design pattern library</LI> <LI>sync.rb 2 phase lock</LI> <LI>telnet.rb telnet library</LI> <LI>tempfile.rb temporary file that automatically removed</LI> <LI>thread.rb thread support</LI> <LI>thwait.rb thread syncronization class</LI> <LI>timeout.rb provids timeout</LI> <LI>tracer.rb execution tracer</LI> <LI>weakref.rb weak reference class</LI>

</UL> <H4><A NAME="39">Classes</A></H4>

<H4><A NAME="40">Modules</A></H4>

<H4><A NAME="41">Mixins</A></H4>

<H4><A NAME="42">Socket</A></H4>

<P>BasicSocket IPSocket TCPSocket SOCKSSocket TCPServer UDPSocket UNIXSocket Socket</P>

<H4><A NAME="43">Net:</A></H4>

<P>FTP HTTP HTTPResponse POP APOP POPMail SMTP Telnet</P>

<H4><A NAME="44">CGI:</A></H4>

<P>CGI CGI::Session</P>

<H4><A NAME="45">MS</A></H4>

<P>WIN32OLE WIN32OLE_EVENT Win32API</P>

<H2><A NAME="46">Tools</A></H2>

<H3><A NAME="47">ruby</A></H3>

<H4><A NAME="48">Command Line Options</A></H4>

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

<H4><A NAME="49">Environment Variables</A></H4>

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

<H3><A NAME="50">irb</A></H3>

<PRE>irb [options] [script [args]]</PRE>

<P>The options are:</P>

<DL>

  • <DT>-f</DT> <DD>Prevents the loading of ~/.irb.rc. Version 1.1 has a bug that swallows the next argument.</DD>

    <DT>-m</DT> <DD>Math mode. Overrides --inspect. Loads "mathn.rb".</DD>

    <DT>-d</DT> <DD>Sets $DEBUG to true. Same as "ruby -d ..."</DD>

    <DT>-r module</DT> <DD>Loads a module. Same as "ruby -r module ..."</DD>

    <DT>--inspect</DT> <DD>Turns on inspect mode. Default.</DD>

    <DT>--noinspect</DT> <DD>Turns off inspect mode.</DD>

    <DT>--readline</DT> <DD>Turns on readline support. Default.</DD>

    <DT>--noreadline</DT> <DD>Turns off readline support.</DD>

    <DT>--prompt[-mode] prompt</DT> <DD>Sets the prompt. 'prompt' must be one of 'default', 'xmp', 'simple', or 'inf-ruby'.</DD>

    <DT>--noprompt</DT> <DD>Turns off the prompt.</DD>

    <DT>--inf-ruby-mode</DT> <DD>Turns on emacs support and turns off readline.</DD>

    <DT>--sample-book-mode, --simple-prompt</DT> <DD>Same as '--prompt simple'</DD>

    <DT>--tracer</DT> <DD>Turns on trace mode. Version 1.1 has a fatal bug with this flag.</DD>

    <DT>--back-trace-limit</DT> <DD>Sets the amount of backtrace to display in trace mode.</DD>

    <DT>--context-mode</DT> <DD>Sets the context mode (0-3) for multiple contexts. Defaults to 3. Not very clear how/why they differ.</DD>

    <DT>--single-irb</DT> <DD>Turns off multiple bindings (disables the irb command below), I think.</DD>

    <DT>--irb_debug level</DT> <DD>Sets internal debug level. For irb only.</DD>

    <DT>-v, --version</DT> <DD>Prints the version and exits.</DD>

</DL>

<P>Besides arbitrary ruby commands, the special commands are:</P>

<DL>

  • <DT>irb_exit</DT> <DD>Exits the current session, or the program if there are no other sessions.</DD>

    <DT>fork block</DT> <DD>forks and runs the given block.</DD>

    <DT>irb_change_binding args</DT> <DD>Changes to a secified binding.</DD>

    <DT>source file</DT> <DD>Loads a ruby file into the session.</DD>

    <DT>irb [obj]</DT> <DD>Starts a new session, with obj as self, if specified.</DD>

    <DT>conf[.key[= val]]</DT> <DD>Access the configuration of the session. May read and write single values.</DD>

    <DT>jobs</DT> <DD>Lists the known sessions.</DD>

    <DT>fg (session#|thread-id|obj|self)</DT> <DD>Switches to the specifed session.</DD>

    <DT>kill session</DT> <DD>Kills a specified session. Session may be specified the same as 'fg'.</DD>

</DL>

<H3><A NAME="51">rtags</A></H3>

<P>TODO: write content</P>

<H3><A NAME="52">xmp</A></H3>

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

<H3><A NAME="53">ruby-mode</A></H3>

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

<H3><A NAME="54">Debugger</A></H3>

<P>To invoke the debugger:</P>

<PRE>ruby -r debug ...</PRE>

Note: With 1.8.2 it appears you have to use: <PRE>ruby -rubygems -r debug ...</PRE>

<P>To use the debugger:</P>

<DL>

  • <DT><CODE>b[reak] [(Missing file: File:/]line) file:]line</CODE></DT> <DD>Set breakpoint at given line in file (default current file).</DD>

    <DT><CODE>b[reak] [(Missing file: File:/]name) file:]name</CODE></DT> <DD>Set breakpoint at method in file.</DD>

    <DT><CODE>b[reak]</CODE></DT> <DD>Display breakpoints and watchpoints.</DD>

    <DT><CODE>wat[ch] expr</CODE></DT> <DD>Break when expression becomes true.</DD>

    <DT><CODE>del[ete] [nnn]</CODE></DT> <DD>Delete breakpoint nnn (default all).</DD>

    <DT><CODE>disp[lay] expr</CODE></DT> <DD>Display value of nnn every time debugger gets control.</DD>

    <DT><CODE>disp[lay]</CODE></DT> <DD>Show current displays.</DD>

    <DT><CODE>undisp[lay] [nnn]</CODE></DT> <DD>Remove display (default all).</DD>

    <DT><CODE>c[ont]</CODE></DT> <DD>Continue execution.</DD>

    <DT><CODE>s[tep] nnn=1</CODE></DT> <DD>Execute next nnn lines, stepping into methods.</DD>

    <DT><CODE>n[ext] nnn=1</CODE></DT> <DD>Execute next nnn lines, stepping over methods.</DD>

    <DT><CODE>fi[nish]</CODE></DT> <DD>Finish execution of the current function.</DD>

    <DT><CODE>q[uit]</CODE></DT> <DD>Exit the debugger.</DD>

    <DT><CODE>w[here]</CODE></DT> <DD>Display current stack frame.</DD>

    <DT><CODE>f[rame]</CODE></DT> <DD>Synonym for where.</DD>

    <DT><CODE>l[ist] [start--end]</CODE></DT> <DD>List source lines from start to end.</DD>

    <DT><CODE>up nnn=1</CODE></DT> <DD>Move up nnn levels in the stack frame.</DD>

    <DT><CODE>down nnn=1</CODE></DT> <DD>Move down nnn levels in the stack frame.</DD>

    <DT><CODE>v[ar] g[lobal]</CODE></DT> <DD>Display global variables.</DD>

    <DT><CODE>v[ar] l[ocal]</CODE></DT> <DD>Display local variables.</DD>

    <DT><CODE>v[ar] i[nstance] obj</CODE></DT> <DD>Display instance variables of obj.</DD>

    <DT><CODE>v[ar] c[onst] Name</CODE></DT> <DD>Display constants in class or module name.</DD>

    <DT><CODE>m[ethod] i[nstance] obj</CODE></DT> <DD>Display instance methods of obj.</DD>

    <DT><CODE>m[ethod] Name</CODE></DT> <DD>Display instance methods of the class or module name.</DD>

    <DT><CODE>th[read] l[ist]</CODE></DT> <DD>List all threads.</DD>

    <DT><CODE>th[read] [c[ur[rent]]]</CODE></DT> <DD>Display status of current thread.</DD>

    <DT><CODE>th[read] [c[ur[rent]]] nnn</CODE></DT> <DD>Make thread nnn current and stop it.</DD>

    <DT><CODE>th[read] stop nnn</CODE></DT> <DD>Make thread nnn current and stop it.</DD>

    <DT><CODE>th[read] resume nnn</CODE></DT> <DD>Resume thread nnn.</DD>

    <DT><CODE>[p] expr</CODE></DT> <DD>Evaluate expr in the current context. expr may include assignment to variables and method invocations.</DD>

    <DT><CODE>empty</CODE></DT> <DD>A null command repeats the last command.</DD>

</DL>

<H3><A NAME="55">old: Embedded Documentation</A></H3>

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

<P>FIX: there is a lot more to rdtool / rdoc.</P>

<P>FIX: rdtool is deprecated for rdoc.</P>

<H2><A NAME="56">Mindshare, Idiom and Patterns</A></H2>

<H3><A NAME="57">Object Design</A></H3>

<UL>

  • <LI>Visitor Pattern (method :each)</LI> <LI>Library delegate (class SimpleDelegator, class DelegateClass)</LI> <LI>Module observer</LI> <LI>Module singleton</LI>

</UL> <H3><A NAME="58">Other Third-party Libraries</A></H3>

<H4><A NAME="59">Amstd</A></H4>

<UL>

  • <LI>amstd/bench.rb</LI> <LI>amstd/bug.rb</LI> <LI>amstd/collfrom.rb</LI> <LI>amstd/constdef.rb</LI> <LI>amstd/dispatch.rb</LI> <LI>amstd/errutil.rb</LI> <LI>amstd/extmod.rb</LI> <LI>amstd/fileutils.rb</LI> <LI>amstd/futils.rb</LI> <LI>amstd/gconst.rb</LI> <LI>amstd/getdep.rb</LI> <LI>amstd/info.rb</LI> <LI>amstd/must.rb</LI> <LI>amstd/pipeline.rb</LI> <LI>amstd/rbparams.rb</LI> <LI>amstd/recycle.rb</LI> <LI>amstd/rubyemu.rb</LI> <LI>amstd/strquote.rb</LI> <LI>amstd/symbol.rb</LI> <LI>amstd/timer.rb</LI> <LI>amstd/to_s.rb</LI> <LI>amstd/version.rb</LI>

</UL> <H4><A NAME="60">Racc</A></H4>

<UL>

  • <LI>racc/parser.rb</LI> <LI>racc/libracc.rb</LI> <LI>racc/facade.rb</LI> <LI>racc/ucodep.rb</LI> <LI>racc/raccs.rb</LI> <LI>racc/iset.rb</LI> <LI>racc/grammer.rb</LI> <LI>racc/state.rb</LI> <LI>racc/format.rb</LI> <LI>racc/info.rb</LI> <LI>racc/raccp.rb</LI>

</UL> <H4><A NAME="61">Optparse</A></H4>

<UL>

  • <LI>optparse/shellwords.rb</LI> <LI>optparse/time.rb</LI> <LI>optparse.rb</LI>

</UL> <H4><A NAME="62">Test::Unit</A></H4>

<UL>

  • <LI>assert_block(message="assert_block failed.") # :yields: </LI> <LI>assert(boolean, message=nil)</LI> <LI>assert_equal(expected, actual, message=nil)</LI> <LI>assert_raises(expected_exception_klass, message="")</LI> <LI>assert_instance_of(klass, object, message="")</LI> <LI>assert_nil(object, message="")</LI> <LI>assert_kind_of(klass, object, message="")</LI> <LI>assert_respond_to(object, method, message="")</LI> <LI>assert_match(pattern, string, message="")</LI> <LI>assert_same(expected, actual, message="")</LI> <LI>assert_operator(object1, operator, object2, message="")</LI> <LI>assert_nothing_raised(*args)</LI> <LI>flunk(message="Flunked")</LI> <LI>assert_not_same(expected, actual, message="")</LI> <LI>assert_not_equal(expected, actual, message="")</LI> <LI>assert_not_nil(object, message="")</LI> <LI>assert_no_match(regexp, string, message="")</LI> <LI>assert_throws(expected_symbol, message="", &proc)</LI> <LI>assert_nothing_thrown(message="", &proc)</LI> <LI>assert_in_delta(expected_float, actual_float, delta, message="")</LI> <LI>assert_send(send_array, message="")</LI>

</UL>

Kevin's notes: <UL> <li>You find executable gem/rubygem code in /usr/local/lib/ruby/gems/1.8/gems/[gem-name]/lib/[code-file].rb <li>You also find gem/rubygem code in /usr/lib/ruby/gems/1.8/gems/[gem-name]/lib/[code-file].rb, but this code does not appear to get executed at runtime. </UL>

Tags:
none
 
Images (0)
 
Comments (0)
You must login to post a comment.