- •Programming Ruby The Pragmatic Programmer's Guide
- •Foreword
- •Preface
- •Ruby Sparkles
- •What Kind of Language Is Ruby?
- •Is Ruby for Me?
- •Why Did We Write This Book?
- •Ruby Versions
- •Installing Ruby
- •Building Ruby
- •Running Ruby
- •Interactive Ruby
- •Ruby Programs
- •Resources
- •Acknowledgments
- •Notation Conventions
- •Roadmap
- •Ruby.New
- •Ruby Is an Object-Oriented Language
- •Some Basic Ruby
- •Arrays and Hashes
- •Control Structures
- •Regular Expressions
- •Blocks and Iterators
- •Reading and 'Riting
- •Onward and Upward
- •Classes, Objects, and Variables
- •Inheritance and Messages
- •Inheritance and Mixins
- •Objects and Attributes
- •Writable Attributes
- •Virtual Attributes
- •Class Variables and Class Methods
- •Class Variables
- •Class Methods
- •Singletons and Other Constructors
- •Access Control
- •Specifying Access Control
- •Variables
- •Containers, Blocks, and Iterators
- •Containers
- •Implementing a SongList Container
- •Blocks and Iterators
- •Implementing Iterators
- •Blocks for Transactions
- •Blocks Can Be Closures
- •Standard Types
- •Numbers
- •Strings
- •Working with Strings
- •Ranges as Sequences
- •Ranges as Conditions
- •Ranges as Intervals
- •Regular Expressions
- •Patterns
- •Anchors
- •Character Classes
- •Repetition
- •Alternation
- •Grouping
- •Pattern-Based Substitution
- •Backslash Sequences in the Substitution
- •Object-Oriented Regular Expressions
- •More About Methods
- •Defining a Method
- •Variable-Length Argument Lists
- •Methods and Blocks
- •Calling a Method
- •Expanding Arrays in Method Calls
- •Making Blocks More Dynamic
- •Collecting Hash Arguments
- •Expressions
- •Operator Expressions
- •Miscellaneous Expressions
- •Command Expansion
- •Backquotes Are Soft
- •Assignment
- •Parallel Assignment
- •Nested Assignments
- •Other Forms of Assignment
- •Conditional Execution
- •Boolean Expressions
- •Defined?, And, Or, and Not
- •If and Unless Expressions
- •If and Unless Modifiers
- •Case Expressions
- •Iterators
- •Break, Redo, and Next
- •Variable Scope and Loops
- •Exceptions, Catch, and Throw
- •The Exception Class
- •Handling Exceptions
- •Tidying Up
- •Play It Again
- •Raising Exceptions
- •Adding Information to Exceptions
- •Catch and Throw
- •Modules
- •Namespaces
- •Instance Variables in Mixins
- •Iterators and the Enumerable Module
- •Including Other Files
- •Basic Input and Output
- •What Is an io Object?
- •Opening and Closing Files
- •Reading and Writing Files
- •Iterators for Reading
- •Writing to Files
- •Talking to Networks
- •Threads and Processes
- •Multithreading
- •Creating Ruby Threads
- •Manipulating Threads
- •Thread Variables
- •Threads and Exceptions
- •Controlling the Thread Scheduler
- •Mutual Exclusion
- •The Mutex Class
- •Condition Variables
- •Running Multiple Processes
- •Spawning New Processes
- •Independent Children
- •Blocks and Subprocesses
- •When Trouble Strikes
- •Ruby Debugger
- •Interactive Ruby
- •Editor Support
- •But It Doesn't Work!
- •But It's Too Slow!
- •Create Locals Outside Blocks
- •Use the Profiler
- •Ruby and Its World
- •Command-Line Arguments
- •Command-Line Options
- •Program Termination
- •Environment Variables
- •Writing to Environment Variables
- •Where Ruby Finds Its Modules
- •Build Environment
- •Ruby and the Web
- •Writing cgi Scripts
- •Using cgi.Rb
- •Quoting
- •Creating Forms and html
- •Cookies
- •Sessions
- •Embedding Ruby in html
- •Using eruby
- •Installing eruby in Apache
- •Improving Performance
- •Ruby Tk
- •Simple Tk Application
- •Widgets
- •Setting Widget Options
- •Getting Widget Data
- •Setting/Getting Options Dynamically
- •Sample Application
- •Binding Events
- •Scrolling
- •Just One More Thing
- •Translating from Perl/Tk Documentation
- •Object Creation
- •Running Ruby Under Windows
- •Windows Automation
- •Getting and Setting Properties
- •Named Arguments
- •For each
- •An Example
- •Optimizing
- •Extending Ruby
- •Ruby Objects in c
- •Value as a Pointer
- •Value as an Immediate Object
- •Writing Ruby in c
- •Evaluating Ruby Expressions in c
- •Sharing Data Between Ruby and c
- •Directly Sharing Variables
- •Wrapping c Structures
- •An Example
- •Memory Allocation
- •Creating an Extension
- •Creating a Makefile with extconf.Rb
- •Static Linking
- •Embedding a Ruby Interpreter
- •Bridging Ruby to Other Languages
- •Ruby c Language api
- •The Ruby Language
- •Source Layout
- •Begin and end Blocks
- •General Delimited Input
- •The Basic Types
- •Integer and Floating Point Numbers
- •Strings
- •Requirements for a Hash Key
- •Symbols
- •Regular Expressions
- •Regular Expression Options
- •Regular Expression Patterns
- •Substitutions
- •Extensions
- •Variable/Method Ambiguity
- •Variables and Constants
- •Scope of Constants and Variables
- •Predefined Variables
- •Exception Information
- •Pattern Matching Variables
- •Input/Output Variables
- •Execution Environment Variables
- •Standard Objects
- •Global Constants
- •Expressions Single Terms
- •Operator Expressions
- •More on Assignment
- •Parallel Assignment
- •Block Expressions
- •Boolean Expressions
- •Truth Values
- •And, Or, Not, and Defined?
- •Comparison Operators
- •Ranges in Boolean Expressions
- •Regular Expressions in Boolean Expressions
- •While and Until Modifiers
- •Break, Redo, Next, and Retry
- •Method Definition
- •Method Arguments
- •Invoking a Method
- •Class Definition
- •Creating Objects from Classes
- •Class Attribute Declarations
- •Module Definitions
- •Mixins---Including Modules
- •Module Functions
- •Access Control
- •Blocks, Closures, and Proc Objects
- •Proc Objects
- •Exceptions
- •Raising Exceptions
- •Handling Exceptions
- •Retrying a Block
- •Catch and Throw
- •Classes and Objects
- •How Classes and Objects Interact
- •Your Basic, Everyday Object
- •Object-Specific Classes
- •Mixin Modules
- •Extending Objects
- •Class and Module Definitions
- •Class Names Are Constants
- •Inheritance and Visibility
- •Freezing Objects
- •Locking Ruby in the Safe
- •Safe Levels
- •Tainted Objects
- •Reflection, ObjectSpace, and Distributed Ruby
- •Looking at Objects
- •Looking Inside Objects
- •Looking at Classes
- •Looking Inside Classes
- •Calling Methods Dynamically
- •Performance Considerations
- •System Hooks
- •Runtime Callbacks
- •Tracing Your Program's Execution
- •How Did We Get Here?
- •Marshaling and Distributed Ruby
- •Custom Serialization Strategy
- •Distributed Ruby
- •Compile Time? Runtime? Anytime!
- •Standard Library
Ruby and Its World
It's an unfortunate fact of life that our applications have to deal with the big, bad world. In this chapter, we'll look at how Ruby interacts with its environment. Microsoft Windows users will probably also want to look at platform-specific information beginning on page 163.
Command-Line Arguments
``In the Beginning was the Command Line.''[Title of a marvelous essay by Neal Stephenson (available online at http://www.spack.org/essays/commandline.html).]Regardless of the system in which Ruby is deployed, whether it be a super high-end scientific graphics workstation or an embedded PDA device, you've got to start the Ruby interpreter somehow, and that gives us the opportunity to pass in command-line arguments.
A Ruby command line consists of three parts: options to the Ruby interpreter, optionally the name of a program to run, and optionally a set of arguments for that program.
ruby [ options ][--][ programfile ][ arguments ] |
The Ruby options are terminated by the first word on the command line that doesn't start with a hyphen, or by the special flag ``--'' (two hyphens).
If no filename is present on the command line, or if the filename is a single hyphen (-), Ruby reads the program source from standard input.
Arguments for the program itself follow the program name. For example:
% ruby -w - "Hello World"
will enable warnings, read a program from standard input, and pass it the quoted string "Hello World"as an argument.
Command-Line Options
-0[octal}
' The number ``0'' flag specifies the record separator character (\0, if no digit follows). -00indicates paragraph mode: records are separated by two successive default record separator characters.-0777reads the entire file at once (as it is an illegal character). Sets$/.
-a
' Auto split mode when used with -nor-p; equivalent to executing {$F at the top of each loop iteration.
-C directory
' Changes working directory to directorybefore executing.
-c
' Checks syntax only; does not execute the program.
--copyright
Prints the copyright notice and exits.
-d, --debug
' Sets $DEBUGto true. This can be used by your programs to enable additional tracing.
-e 'command'
' Executes commandas one line of Ruby source. Several-e's are allowed, and the commands are treated as multiple lines in the same program. Ifprogramfileis omitted when-eis present, execution stops after the-ecommands have been run.
-F pattern
' Specifies the input field separator ($;) used as the default forsplit()(affects-a).
-h, --help
' Displays a short help screen.
-I directories
' Specifies directories to be prepended to $LOAD_PATH($:). Multiple-Ioptions may be present, and multiple directories may appear following each-I. Directories are separated by a ``:'' on Unix-like systems and by a ``;'' on DOS/Windows systems.
-i [extension}
' Edits ARGVfiles in place. For each file named inARGV, anything you write to standard output will be saved back as the contents of that file. A backup copy of the file will be made ifextensionis supplied.
% ruby -pi.bak -e "gsub(/Perl/, 'Ruby')" *.txt
-K kcode
' Specifies the code set to be used. This option is useful mainly when Ruby is used for Japanese-language processing. kcodemay be one of: e, E for EUC; s, S for SJIS; u, U for UTF-8; or a, A, n, N for ASCII.
-l
' Enables automatic line-ending processing; sets $\to the value of$/and chops every input line automatically.
-n
' Assumes ``while gets; ...; end'' loop around your program. For example, a simplegrepcommand might be implemented as:
% ruby -n -e "print if /wombat/" *.txt
-p
' Places your program code within the loop ``while gets; ...; print; end.''
% ruby -p -e "$_.downcase!" *.txt
-r library
' requires the named library before executing.
-S
' Looks for the program file using RUBYPATHorPATHenvironment variable.
-s
' Any command line switches found after the program filename, but before any filename arguments or before a --, are removed fromARGVand set to a global variable named for the switch. In the following example, the effect of this would be to set the variable$optto ``electric''.
% ruby -s prog -opt=electric ./mydata
-T[level}
' Sets the safe level, which among other things enables tainting checks (see page 253). Sets $SAFE.
-v, --verbose
' Enables verbose mode and print the version number. In verbose mode, compilation warnings are printed. If no program filename appears on the command line, Ruby exits.
--version
Displays the Ruby version number and exits.
-w
' Enables verbose mode. Unlike -v, reads program from standard input if no program files are present on the command line. We recommend running your Ruby programs with-w.
-X directory
' Changes working directory to directorybefore executing. Same as-Cdirectory.
-x [directory}
' Strips off text before #!rubyline and changes working directory todirectoryif given.
-y, --yydebug
' Enables yacc debugging in the parser (waaay too much information).
ARGV
Any command-line arguments after the program filename are available to your Ruby program in the global array ARGV. For instance, invoking Ruby as
% ruby -w ptest "Hello World" a1 1.6180
yields an ARGVarray containing["Hello World", a1, 1.6180]. There's a gotcha here for all you C programmers---ARGV[0]is the first argument to the program, not the program name. The name of the current program is available in the global variable$0.