You are previewing The Ruby Programming Language.
O'Reilly logo
The Ruby Programming Language

Book Description

The Ruby Programming Language is the authoritative guide to Ruby and provides comprehensive coverage of versions 1.8 and 1.9 of the language. It was written (and illustrated!) by an all-star team:

  • David Flanagan, bestselling author of programming language "bibles" (including JavaScript: The Definitive Guide and Java in a Nutshell) and committer to the Ruby Subversion repository.

  • Yukihiro "Matz" Matsumoto, creator, designer and lead developer of Ruby and author of Ruby in a Nutshell, which has been expanded and revised to become this book.

  • why the lucky stiff, artist and Ruby programmer extraordinaire.

This book begins with a quick-start tutorial to the language, and then explains the language in detail from the bottom up: from lexical and syntactic structure to datatypes to expressions and statements and on through methods, blocks, lambdas, closures, classes and modules.

The book also includes a long and thorough introduction to the rich API of the Ruby platform, demonstrating -- with heavily-commented example code -- Ruby's facilities for text processing, numeric manipulation, collections, input/output, networking, and concurrency. An entire chapter is devoted to Ruby's metaprogramming capabilities.

The Ruby Programming Language documents the Ruby language definitively but without the formality of a language specification. It is written for experienced programmers who are new to Ruby, and for current Ruby programmers who want to challenge their understanding and increase their mastery of the language.

Table of Contents

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