Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
The Ruby Programming Language
A Note Regarding Supplemental Files
Preface
Acknowledgments
David Flanagan
Yukihiro Matsumoto
Conventions Used in This Book
Using Code Examples
How to Contact Us
Safari® Enabled
1. Introduction
A Tour of Ruby
Ruby Is Object-Oriented
Blocks and Iterators
Expressions and Operators in Ruby
Methods
Assignment
Punctuation Suffixes and Prefixes
Regexp and Range
Classes and Modules
Ruby Surprises
Try Ruby
The Ruby Interpreter
Displaying Output
Interactive Ruby with irb
Viewing Ruby Documentation with ri
Ruby Package Management with gem
More Ruby Tutorials
Ruby Resources
About This Book
How to Read This Book
A Sudoku Solver in Ruby
2. The Structure and Execution of Ruby Programs
Lexical Structure
Comments
Embedded documents
Documentation comments
Literals
Punctuation
Identifiers
Case sensitivity
Unicode characters in identifiers
Punctuation in identifiers
Keywords
Whitespace
Newlines as statement terminators
Spaces and method invocations
Syntactic Structure
Block Structure in Ruby
File Structure
Program Encoding
Specifying Program Encoding
Source, External, and Internal Encodings
Program Execution
3. Datatypes and Objects
Numbers
Integer Literals
Floating-Point Literals
Arithmetic in Ruby
Binary Floating-Point and Rounding Errors
Text
String Literals
Single-quoted string literals
Double-quoted string literals
Unicode escapes
Arbitrary delimiters for string literals
Here documents
Backtick command execution
String literals and mutability
The String.new method
Character Literals
String Operators
Accessing Characters and Substrings
Iterating Strings
String Encodings and Multibyte Characters
Multibyte characters in Ruby 1.9
The Encoding class
Multibyte characters in Ruby 1.8
Arrays
Hashes
Hash Literals
Hash Codes, Equality, and Mutable Keys
Ranges
Testing Membership in a Range
Symbols
True, False, and Nil
Objects
Object References
Immediate values
Object Lifetime
Object Identity
Object Class and Object Type
Object Equality
The equal? method
The == operator
The eql? method
The === operator
The =~ operator
Object Order
Object Conversion
Explicit conversions
Implicit conversions
Conversion functions
Arithmetic operator type coercions
Boolean type conversions
Copying Objects
Marshaling Objects
Freezing Objects
Tainted and Untrusted Objects
4. Expressions and Operators
Literals and Keyword Literals
Variable References
Uninitialized Variables
Constant References
Method Invocations
Assignments
Assigning to Variables
Assigning to Constants
Assigning to Attributes and Array Elements
Abbreviated Assignment
Parallel Assignment
Same number of lvalues and rvalues
One lvalue, multiple rvalues
Multiple lvalues, single array rvalue
Different numbers of lvalues and rvalues
The splat operator
Parentheses in parallel assignment
The value of parallel assignment
Operators
Unary + and –
Exponentiation: **
Arithmetic: +, –, *, /, and %
Shift and Append: << and >>
Complement, Union, Intersection: ~, &, |, and ^
Comparison: <, <=, >, >=, and <=>
Equality: ==, !=, =~, !~, and ===
Boolean Operators: &&, ||, !, and, or, not
Ranges and Flip-Flops: .. and ...
Boolean flip-flops
Conditional: ?:
Assignment Operators
The defined? Operator
Statement Modifiers
Nonoperators
5. Statements and Control Structures
Conditionals
if
else
elsif
Return value
if As a Modifier
unless
case
The ?: Operator
Loops
while and until
while and until As Modifiers
The for/in Loop
Iterators and Enumerable Objects
Numeric Iterators
Enumerable Objects
Writing Custom Iterators
Enumerators
External Iterators
Iteration and Concurrent Modification
Blocks
Block Syntax
The Value of a Block
Blocks and Variable Scope
Passing Arguments to a Block
Block Parameters in Ruby 1.9
Altering Control Flow
return
break
break with a value
next
next and block value
redo
retry
throw and catch
Exceptions and Exception Handling
Exception Classes and Exception Objects
The methods of exception objects
Creating exception objects
Defining new exception classes
Raising Exceptions with raise
Handling Exceptions with rescue
Naming the exception object
Handling exceptions by type
Propagation of exceptions
Exceptions during exception handling
retry in a rescue clause
The else Clause
The ensure Clause
rescue with Method, Class, and Module Definitions
rescue As a Statement Modifier
BEGIN and END
Threads, Fibers, and Continuations
Threads for Concurrency
Fibers for Coroutines
Fiber arguments and return values
Implementing generators with fibers
Advanced fiber features
Continuations
6. Methods, Procs, Lambdas, and Closures
Defining Simple Methods
Method Return Value
Methods and Exception Handling
Invoking a Method on an Object
Defining Singleton Methods
Undefining Methods
Method Names
Operator Methods
Method Aliases
Methods and Parentheses
Optional Parentheses
Required Parentheses
Method Arguments
Parameter Defaults
Variable-Length Argument Lists and Arrays
Passing arrays to methods
Mapping Arguments to Parameters
Hashes for Named Arguments
Block Arguments
Using & in method invocation
Procs and Lambdas
Creating Procs
Proc.new
Kernel.lambda
Kernel.proc
Lambda Literals
Invoking Procs and Lambdas
The Arity of a Proc
Proc Equality
How Lambdas Differ from Procs
Return in blocks, procs, and lambdas
Break in blocks, procs and lambdas
Other control-flow statements
Argument passing to procs and lambdas
Closures
Closures and Shared Variables
Closures and Bindings
Method Objects
Unbound Method Objects
Functional Programming
Applying a Function to an Enumerable
Composing Functions
Partially Applying Functions
Memoizing Functions
Symbols, Methods, and Procs
7. Classes and Modules
Defining a Simple Class
Creating the Class
Instantiating a Point
Initializing a Point
Defining a to_s Method
Accessors and Attributes
Defining Operators
Array and Hash Access with [ ]
Enumerating Coordinates
Point Equality
Ordering Points
A Mutable Point
Quick and Easy Mutable Classes
A Class Method
Constants
Class Variables
Class Instance Variables
Method Visibility: Public, Protected, Private
Subclassing and Inheritance
Inheriting Methods
Overriding Methods
Overriding private methods
Augmenting Behavior by Chaining
Inheritance of Class Methods
Inheritance and Instance Variables
Inheritance and Class Variables
Inheritance of Constants
Object Creation and Initialization
new, allocate, and initialize
Factory Methods
dup, clone, and initialize_copy
marshal_dump and marshal_load
The Singleton Pattern
Modules
Modules as Namespaces
Nested namespaces
Modules As Mixins
Includable Namespace Modules
Loading and Requiring Modules
The Load Path
Executing Loaded Code
Wrapped loads
Autoloading Modules
Singleton Methods and the Eigenclass
Method Lookup
Class Method Lookup
Constant Lookup
8. Reflection and Metaprogramming
Types, Classes, and Modules
Ancestry and Modules
Defining Classes and Modules
Evaluating Strings and Blocks
Bindings and eval
instance_eval and class_eval
instance_exec and class_exec
Variables and Constants
Querying, Setting, and Testing Variables
Methods
Listing and Testing For Methods
Obtaining Method Objects
Invoking Methods
Defining, Undefining, and Aliasing Methods
Handling Undefined Methods
Setting Method Visibility
Hooks
Tracing
ObjectSpace and GC
Custom Control Structures
Delaying and Repeating Execution: after and every
Thread Safety with Synchronized Blocks
Missing Methods and Missing Constants
Unicode Codepoint Constants with const_missing
Tracing Method Invocations with method_missing
Synchronized Objects by Delegation
Dynamically Creating Methods
Defining Methods with class_eval
Defining Methods with define_method
Alias Chaining
Tracing Files Loaded and Classes Defined
Chaining Methods for Thread Safety
Chaining Methods for Tracing
Domain-Specific Languages
Simple XML Output with method_missing
Validated XML Output with Method Generation
9. The Ruby Platform
Strings
Formatting Text
Packing and Unpacking Binary Strings
Strings and Encodings
Regular Expressions
Regexp Literals
Regexp Factory Methods
Regular Expression Syntax
Pattern Matching with Regular Expressions
Global variables for match data
Pattern matching with strings
Search and replace
Regular expression encoding
Numbers and Math
Numeric Methods
The Math Module
Decimal Arithmetic
Complex Numbers
Rational Numbers
Vectors and Matrices
Random Numbers
Dates and Times
Collections
Enumerable Objects
Iterating and converting collections
Enumerators and external iterators
Sorting collections
Searching collections
Selecting subcollections
Reducing collections
Arrays
Creating arrays
Array size and elements
Altering array elements
Iterating, searching, and sorting arrays
Array comparison
Arrays as stacks and queues
Arrays as sets
Associative array methods
Miscellaneous array methods
Hashes
Creating hashes
Indexing hashes and testing membership
Storing keys and values in a hash
Removing hash entries
Arrays from hashes
Hash iterators
Default values
Hashcodes, key equality, and mutable keys
Miscellaneous hash methods
Sets
Creating sets
Testing, comparing, and combining Sets
Adding and deleting set elements
Set iterators
Miscellaneous set methods
Files and Directories
File and Directory Names
Listing Directories
Testing Files
Creating, Deleting, and Renaming Files and Directories
Input/Output
Opening Streams
Opening files
Kernel.open
StringIO
Predefined streams
Streams and Encodings
Reading from a Stream
Reading lines
Reading entire files
Reading bytes and characters
Writing to a Stream
Random Access Methods
Closing, Flushing, and Testing Streams
Networking
A Very Simple Client
A Very Simple Server
Datagrams
A More Complex Client
A Multiplexing Server
Fetching Web Pages
Threads and Concurrency
Thread Lifecycle
The main thread
Threads and unhandled exceptions
Threads and Variables
Thread-private variables
Thread-local variables
Thread Scheduling
Thread priorities
Thread preemption and Thread.pass
Thread States
Querying thread state
Altering state: pausing, waking, and killing threads
Listing Threads and Thread Groups
Threading Examples
Reading files concurrently
A Multithreaded Server
Concurrent iterators
Thread Exclusion and Deadlock
Deadlock
Queue and SizedQueue
Condition Variables and Queues
10. The Ruby Environment
Invoking the Ruby Interpreter
Common Options
Warnings and Information Options
Encoding Options
Text Processing Options
Miscellaneous Options
The Top-Level Environment
Predefined Modules and Classes
Top-Level Constants
Global Variables
Global settings
Exception-handling globals
Streams and text-processing globals
Pattern-matching globals
Command-line option globals
Predefined Global Functions
Keyword functions
Text input, output, and manipulation functions
OS methods
Warnings, failures, and exiting
Reflection functions
Conversion functions
Miscellaneous Kernel functions
User-Defined Global Functions
Practical Extraction and Reporting Shortcuts
Input Functions
Deprecated Extraction Functions
Reporting Functions
One-Line Script Shortcuts
Calling the OS
Invoking OS Commands
Forking and Processes
Trapping Signals
Terminating Programs
Security
Tainted Data
Restricted Execution and Safe Levels
Safe level 0
Safe Level 1
Safe level 2
Safe level 3
Safe level 4
Index
About the Authors
Colophon
← Prev
Back
Next →
← Prev
Back
Next →