Ruby Cookbook

book cover
Ruby Cookbook
By Lucas Carlson, Leonard Richardson
Publisher: O'Reilly
Pub Date: July 2006
Print ISBN-10: 0-596-52369-6
Print ISBN-13: 978-0-59-652369-5
Pages: 906

Table of Contents  | Index

Do you want to push Ruby to its limits? The Ruby Cookbook
is the most comprehensive problem-solving guide to today's hottest
language. It gives you hundreds of solutions to real-world problems,
with clear explanations and thousands of lines of code you can use in
your own projects.

From data structures and algorithms, to integration with
cutting-edge technologies, the Ruby Cookbook has
something for every programmer. Beginners and advanced Rubyists
alike will learn how to program with:

  • Strings and numbers

  • Arrays and hashes

  • Classes, modules, and namespaces

  • Reflection and metaprogramming

  • XML and HTML processing

  • Ruby on Rails (including Ajax integration)

  • Databases

  • Graphics

  • Internet services like email, SSH, and BitTorrent

  • Web services

  • Multitasking

  • Graphical and terminal interfaces

If you need to write a web application, this book shows you
how to get started with Rails. If you're a system administrator who
needs to
rename thousands of files, you'll see how to use Ruby for this and
other everyday tasks. You'll learn how to read and write Excel
spreadsheets, classify text with Bayesian filters, and create PDF
files. We've even included a few silly tricks that were too cool to
leave out, like how to blink the lights on your keyboard.

The Ruby Cookbook is the most useful book yet
written about Ruby. When you need to solve a problem, don't reinvent
the wheel: look it up in
the Cookbook.

book cover
Ruby Cookbook
By Lucas Carlson, Leonard Richardson
Publisher: O'Reilly
Pub Date: July 2006
Print ISBN-10: 0-596-52369-6
Print ISBN-13: 978-0-59-652369-5
Pages: 906

Table of Contents  | Index

        Chapter 1.  Strings
      Recipe 1.1.  Building a String from Parts
      Recipe 1.2.  Substituting Variables into Strings
      Recipe 1.3.  Substituting Variables into an Existing String
      Recipe 1.4.  Reversing a String by Words or Characters
      Recipe 1.5.  Representing Unprintable Characters
      Recipe 1.6.  Converting Between Characters and Values
      Recipe 1.7.  Converting Between Strings and Symbols
      Recipe 1.8.  Processing a String One Character at a Time
      Recipe 1.9.  Processing a String One Word at a Time
      Recipe 1.10.  Changing the Case of a String
      Recipe 1.11.  Managing Whitespace
      Recipe 1.12.  Testing Whether an Object Is String-Like
      Recipe 1.13.  Getting the Parts of a String You Want
      Recipe 1.14.  Handling International Encodings
      Recipe 1.15.  Word-Wrapping Lines of Text
      Recipe 1.16.  Generating a Succession of Strings
      Recipe 1.17.  Matching Strings with Regular Expressions
      Recipe 1.18.  Replacing Multiple Patterns in a Single Pass
      Recipe 1.19.  Validating an Email Address
      Recipe 1.20.  Classifying Text with a Bayesian Analyzer
        Chapter 2.  Numbers
      Recipe 2.1.  Parsing a Number from a String
      Recipe 2.2.  Comparing Floating-Point Numbers
      Recipe 2.3.  Representing Numbers to Arbitrary Precision
      Recipe 2.4.  Representing Rational Numbers
      Recipe 2.5.  Generating Random Numbers
      Recipe 2.6.  Converting Between Numeric Bases
      Recipe 2.7.  Taking Logarithms
      Recipe 2.8.  Finding Mean, Median, and Mode
      Recipe 2.9.  Converting Between Degrees and Radians
      Recipe 2.10.  Multiplying Matrices
      Recipe 2.11.  Solving a System of Linear Equations
      Recipe 2.12.  Using Complex Numbers
      Recipe 2.13.  Simulating a Subclass of Fixnum
      Recipe 2.14.  Doing Math with Roman Numbers
      Recipe 2.15.  Generating a Sequence of Numbers
      Recipe 2.16.  Generating Prime Numbers
      Recipe 2.17.  Checking a Credit Card Checksum
        Chapter 3.  Date and Time
      Recipe 3.1.  Finding Today's Date
      Recipe 3.2.  Parsing Dates, Precisely or Fuzzily
      Recipe 3.3.  Printing a Date
      Recipe 3.4.  Iterating Over Dates
      Recipe 3.5.  Doing Date Arithmetic
      Recipe 3.6.  Counting the Days Since an Arbitrary Date
      Recipe 3.7.  Converting Between Time Zones
      Recipe 3.8.  Checking Whether Daylight Saving Time Is in Effect
      Recipe 3.9.  Converting Between Time and DateTime Objects
      Recipe 3.10.  Finding the Day of the Week
      Recipe 3.11.  Handling Commercial Dates
      Recipe 3.12.  Running a Code Block Periodically
      Recipe 3.13.  Waiting a Certain Amount of Time
      Recipe 3.14.  Adding a Timeout to a Long-Running Operation
        Chapter 4.  Arrays
      Recipe 4.1.  Iterating Over an Array
      Recipe 4.2.  Rearranging Values Without Using Temporary Variables
      Recipe 4.3.  Stripping Duplicate Elements from an Array
      Recipe 4.4.  Reversing an Array
      Recipe 4.5.  Sorting an Array
      Recipe 4.6.  Ignoring Case When Sorting Strings
      Recipe 4.7.  Making Sure a Sorted Array Stays Sorted
      Recipe 4.8.  Summing the Items of an Array
      Recipe 4.9.  Sorting an Array by Frequency of Appearance
      Recipe 4.10.  Shuffling an Array
      Recipe 4.11.  Getting the N Smallest Items of an Array
      Recipe 4.12.  Building Up a Hash Using Injection
      Recipe 4.13.  Extracting Portions of Arrays
      Recipe 4.14.  Computing Set Operations on Arrays
      Recipe 4.15.  Partitioning or Classifying a Set
        Chapter 5.  Hashes
      Recipe 5.1.  Using Symbols as Hash Keys
      Recipe 5.2.  Creating a Hash with a Default Value
      Recipe 5.3.  Adding Elements to a Hash
      Recipe 5.4.  Removing Elements from a Hash
      Recipe 5.5.  Using an Array or Other Modifiable Object as a Hash Key
      Recipe 5.6.  Keeping Multiple Values for the Same Hash Key
      Recipe 5.7.  Iterating Over a Hash
      Recipe 5.8.  Iterating Over a Hash in Insertion Order
      Recipe 5.9.  Printing a Hash
      Recipe 5.10.  Inverting a Hash
      Recipe 5.11.  Choosing Randomly from a Weighted List
      Recipe 5.12.  Building a Histogram
      Recipe 5.13.  Remapping the Keys and Values of a Hash
      Recipe 5.14.  Extracting Portions of Hashes
      Recipe 5.15.  Searching a Hash with Regular Expressions
        Chapter 6.  Files and Directories
      Recipe 6.1.  Checking to See If a File Exists
      Recipe 6.2.  Checking Your Access to a File
      Recipe 6.3.  Changing the Permissions on a File
      Recipe 6.4.  Seeing When a File Was Last Used Problem
      Recipe 6.5.  Listing a Directory
      Recipe 6.6.  Reading the Contents of a File
      Recipe 6.7.  Writing to a File
      Recipe 6.8.  Writing to a Temporary File
      Recipe 6.9.  Picking a Random Line from a File
      Recipe 6.10.  Comparing Two Files
      Recipe 6.11.  Performing Random Access on "Read-Once" Input Streams
      Recipe 6.12.  Walking a Directory Tree
      Recipe 6.13.  Locking a File
      Recipe 6.14.  Backing Up to Versioned Filenames
      Recipe 6.15.  Pretending a String Is a File
      Recipe 6.16.  Redirecting Standard Input or Output
      Recipe 6.17.  Processing a Binary File
      Recipe 6.18.  Deleting a File
      Recipe 6.19.  Truncating a File
      Recipe 6.20.  Finding the Files You Want
      Recipe 6.21.  Finding and Changing the Current Working Directory
        Chapter 7.  Code Blocks and Iteration
      Recipe 7.1.  Creating and Invoking a Block
      Recipe 7.2.  Writing a Method That Accepts a Block
      Recipe 7.3.  Binding a Block Argument to a Variable
      Recipe 7.4.  Blocks as Closures: Using Outside Variables Within a Code Block
      Recipe 7.5.  Writing an Iterator Over a Data Structure
      Recipe 7.6.  Changing the Way an Object Iterates
      Recipe 7.7.  Writing Block Methods That Classify or Collect
      Recipe 7.8.  Stopping an Iteration
      Recipe 7.9.  Looping Through Multiple Iterables in Parallel
      Recipe 7.10.  Hiding Setup and Cleanup in a Block Method
      Recipe 7.11.  Coupling Systems Loosely with Callbacks
        Chapter 8.  Objects and Classes8
      Recipe 8.1.  Managing Instance Data
      Recipe 8.2.  Managing Class Data
      Recipe 8.3.  Checking Class or Module Membership
      Recipe 8.4.  Writing an Inherited Class
      Recipe 8.5.  Overloading Methods
      Recipe 8.6.  Validating and Modifying Attribute Values
      Recipe 8.7.  Defining a Virtual Attribute
      Recipe 8.8.  Delegating Method Calls to Another Object
      Recipe 8.9.  Converting and Coercing Objects to Different Types
      Recipe 8.10.  Getting a Human-Readable Printout of Any Object
      Recipe 8.11.  Accepting or Passing a Variable Number of Arguments
      Recipe 8.12.  Simulating Keyword Arguments
      Recipe 8.13.  Calling a Superclass's Method
      Recipe 8.14.  Creating an Abstract Method
      Recipe 8.15.  Freezing an Object to Prevent Changes
      Recipe 8.16.  Making a Copy of an Object
      Recipe 8.17.  Declaring Constants
      Recipe 8.18.  Implementing Class and Singleton Methods
      Recipe 8.19.  Controlling Access by Making Methods Private
        Chapter 9.  Modules and Namespaces
      Recipe 9.1.  Simulating Multiple Inheritance with Mixins
      Recipe 9.2.  Extending Specific Objects with Modules
      Recipe 9.3.  Mixing in Class Methods
      Recipe 9.4.  Implementing Enumerable: Write One Method, Get 22 Free
      Recipe 9.5.  Avoiding Naming Collisions with Namespaces
      Recipe 9.6.  Automatically Loading Libraries as Needed
      Recipe 9.7.  Including Namespaces
      Recipe 9.8.  Initializing Instance Variables Defined by a Module
      Recipe 9.9.  Automatically Initializing Mixed-In Modules
        Chapter 10.  Reflection and Metaprogramming
      Recipe 10.1.  Finding an Object's Class and Superclass
      Recipe 10.2.  Listing an Object's Methods
      Recipe 10.3.  Listing Methods Unique to an Object
      Recipe 10.4.  Getting a Reference to a Method
      Recipe 10.5.  Fixing Bugs in Someone Else's Class
      Recipe 10.6.  Listening for Changes to a Class
      Recipe 10.7.  Checking Whether an Object Has Necessary Attributes
      Recipe 10.8.  Responding to Calls to Undefined Methods
      Recipe 10.9.  Automatically Initializing Instance Variables
      Recipe 10.10.  Avoiding Boilerplate Code with Metaprogramming
      Recipe 10.11.  Metaprogramming with String Evaluations
      Recipe 10.12.  Evaluating Code in an Earlier Context
      Recipe 10.13.  Undefining a Method
      Recipe 10.14.  Aliasing Methods
      Recipe 10.15.  Doing Aspect-Oriented Programming
      Recipe 10.16.  Enforcing Software Contracts
        Chapter 11.  XML and HTML
      Recipe 11.1.  Checking XML Well-Formedness
      Recipe 11.2.  Extracting Data from a Document's Tree Structure
      Recipe 11.3.  Extracting Data While Parsing a Document
      Recipe 11.4.  Navigating a Document with XPath
      Recipe 11.5.  Parsing Invalid Markup
      Recipe 11.6.  Converting an XML Document into a Hash
      Recipe 11.7.  Validating an XML Document
      Recipe 11.8.  Substituting XML Entities
      Recipe 11.9.  Creating and Modifying XML Documents
      Recipe 11.10.  Compressing Whitespace in an XML Document
      Recipe 11.11.  Guessing a Document's Encoding
      Recipe 11.12.  Converting from One Encoding to Another
      Recipe 11.13.  Extracting All the URLs from an HTML Document
      Recipe 11.14.  Transforming Plain Text to HTML
      Recipe 11.15.  Converting HTML Documents from the Web into Text
      Recipe 11.16.  A Simple Feed Aggregator
        Chapter 12.  Graphics and Other File Formats
      Recipe 12.1.  Thumbnailing Images
      Recipe 12.2.  Adding Text to an Image
      Recipe 12.3.  Converting One Image Format to Another
      Recipe 12.4.  Graphing Data
      Recipe 12.5.  Adding Graphical Context with Sparklines
      Recipe 12.6.  Strongly Encrypting Data
      Recipe 12.7.  Parsing Comma-Separated Data
      Recipe 12.8.  Parsing Not-Quite-Comma-Separated Data
      Recipe 12.9.  Generating and Parsing Excel Spreadsheets
      Recipe 12.10.  Compressing and Archiving Files with Gzip and Tar
      Recipe 12.11.  Reading and Writing ZIP Files
      Recipe 12.12.  Reading and Writing Configuration Files
      Recipe 12.13.  Generating PDF Files
      Recipe 12.14.  Representing Data as MIDI Music
        Chapter 13.  Databases and Persistence
      Recipe 13.1.  Serializing Data with YAML
      Recipe 13.2.  Serializing Data with Marshal
      Recipe 13.3.  Persisting Objects with Madeleine
      Recipe 13.4.  Indexing Unstructured Text with SimpleSearch
      Recipe 13.5.  Indexing Structured Text with Ferret
      Recipe 13.6.  Using Berkeley DB Databases
      Recipe 13.7.  Controlling MySQL on Unix
      Recipe 13.8.  Finding the Number of Rows Returned by a Query
      Recipe 13.9.  Talking Directly to a MySQL Database
      Recipe 13.10.  Talking Directly to a PostgreSQL Database
      Recipe 13.11.  Using Object Relational Mapping with ActiveRecord
      Recipe 13.12.  Using Object Relational Mapping with Og
      Recipe 13.13.  Building Queries Programmatically
      Recipe 13.14.  Validating Data with ActiveRecord
      Recipe 13.15.  Preventing SQL Injection Attacks
      Recipe 13.16.  Using Transactions in ActiveRecord
      Recipe 13.17.  Adding Hooks to Table Events
      Recipe 13.18.  Adding Taggability with a Database Mixin
        Chapter 14.  Internet Services
      Recipe 14.1.  Grabbing the Contents of a Web Page
      Recipe 14.2.  Making an HTTPS Web Request
      Recipe 14.3.  Customizing HTTP Request Headers
      Recipe 14.4.  Performing DNS Queries
      Recipe 14.5.  Sending Mail
      Recipe 14.6.  Reading Mail with IMAP
      Recipe 14.7.  Reading Mail with POP3
      Recipe 14.8.  Being an FTP Client
      Recipe 14.9.  Being a Telnet Client
      Recipe 14.10.  Being an SSH Client
      Recipe 14.11.  Copying a File to Another Machine
      Recipe 14.12.  Being a BitTorrent Client
      Recipe 14.13.  Pinging a Machine
      Recipe 14.14.  Writing an Internet Server
      Recipe 14.15.  Parsing URLs
      Recipe 14.16.  Writing a CGI Script
      Recipe 14.17.  Setting Cookies and Other HTTP Response Headers
      Recipe 14.18.  Handling File Uploads via CGI
      Recipe 14.19.  Running Servlets with WEBrick
      Recipe 14.20.  A Real-World HTTP Client
        Chapter 15.  Web Development: Ruby on Rails
      Recipe 15.1.  Writing a Simple Rails Application to Show System Status
      Recipe 15.2.  Passing Data from the Controller to the View
      Recipe 15.3.  Creating a Layout for Your Header and Footer
      Recipe 15.4.  Redirecting to a Different Location
      Recipe 15.5.  Displaying Templates with Render
      Recipe 15.6.  Integrating a Database with Your Rails Application
      Recipe 15.7.  Understanding Pluralization Rules
      Recipe 15.8.  Creating a Login System
      Recipe 15.9.  Storing Hashed User Passwords in the Database
      Recipe 15.10.  Escaping HTML and JavaScript for Display
      Recipe 15.11.  Setting and Retrieving Session Information
      Recipe 15.12.  Setting and Retrieving Cookies
      Recipe 15.13.  Extracting Code into Helper Functions
      Recipe 15.14.  Refactoring the View into Partial Snippets of Views
      Recipe 15.15.  Adding DHTML Effects with
      Recipe 15.16.  Generating Forms for Manipulating Model Objects
      Recipe 15.17.  Creating an Ajax Form
      Recipe 15.18.  Exposing Web Services on Your Web Site
      Recipe 15.19.  Sending Mail with Rails
      Recipe 15.20.  Automatically Sending Error Messages to Your Email
      Recipe 15.21.  Documenting Your Web Site
      Recipe 15.22.  Unit Testing Your Web Site
      Recipe 15.23.  Using breakpoint in Your Web Application
        Chapter 16.  Web Services and Distributed Programming
      Recipe 16.1.  Searching for Books on Amazon
      Recipe 16.2.  Finding Photos on Flickr
      Recipe 16.3.  Writing an XML-RPC Client
      Recipe 16.4.  Writing a SOAP Client
      Recipe 16.5.  Writing a SOAP Server
      Recipe 16.6.  Searching the Web with Google's SOAP Service
      Recipe 16.7.  Using a WSDL File to Make SOAP Calls Easier
      Recipe 16.8.  Charging a Credit Card
      Recipe 16.9.  Finding the Cost to Ship Packages via UPS or FedEx
      Recipe 16.10.  Sharing a Hash Between Any Number of Computers
      Recipe 16.11.  Implementing a Distributed Queue
      Recipe 16.12.  Creating a Shared "Whiteboard"
      Recipe 16.13.  Securing DRb Services with Access Control Lists
      Recipe 16.14.  Automatically Discovering DRb Services with Rinda
      Recipe 16.15.  Proxying Objects That Can't Be Distributed
      Recipe 16.16.  Storing Data on Distributed RAM with MemCached
      Recipe 16.17.  Caching Expensive Results with MemCached
      Recipe 16.18.  A Remote-Controlled Jukebox
        Chapter 17.  Testing, Debugging, Optimizing, and Documenting
      Recipe 17.1.  Running Code Only in Debug Mode
      Recipe 17.2.  Raising an Exception
      Recipe 17.3.  Handling an Exception
      Recipe 17.4.  Rerunning After an Exception
      Recipe 17.5.  Adding Logging to Your Application
      Recipe 17.6.  Creating and Understanding Tracebacks
      Recipe 17.7.  Writing Unit Tests
      Recipe 17.8.  Running Unit Tests
      Recipe 17.9.  Testing Code That Uses External Resources
      Recipe 17.10.  Using breakpoint to Inspect and Change the State of Your Application
      Recipe 17.11.  Documenting Your Application
      Recipe 17.12.  Profiling Your Application
      Recipe 17.13.  Benchmarking Competing Solutions
      Recipe 17.14.  Running Multiple Analysis Tools at Once
      Recipe 17.15.  Who's Calling That Method? A Call Graph Analyzer
        Chapter 18.  Packaging and Distributing Software
      Recipe 18.1.  Finding Libraries by Querying Gem Respositories
      Recipe 18.2.  Installing and Using a Gem
      Recipe 18.3.  Requiring a Specific Version of a Gem
      Recipe 18.4.  Uninstalling a Gem
      Recipe 18.5.  Reading Documentation for Installed Gems
      Recipe 18.6.  Packaging Your Code as a Gem
      Recipe 18.7.  Distributing Your Gems
      Recipe 18.8.  Installing and Creating Standalone Packages with setup.rb
        Chapter 19.  Automating Tasks with Rake
      Recipe 19.1.  Automatically Running Unit Tests
      Recipe 19.2.  Automatically Generating Documentation
      Recipe 19.3.  Cleaning Up Generated Files
      Recipe 19.4.  Automatically Building a Gem
      Recipe 19.5.  Gathering Statistics About Your Code
      Recipe 19.6.  Publishing Your Documentation
      Recipe 19.7.  Running Multiple Tasks in Parallel
      Recipe 19.8.  A Generic Project Rakefile
        Chapter 20.  Multitasking and Multithreading
      Recipe 20.1.  Running a Daemon Process on Unix
      Recipe 20.2.  Creating a Windows Service
      Recipe 20.3.  Doing Two Things at Once with Threads
      Recipe 20.4.  Synchronizing Access to an Object
      Recipe 20.5.  Terminating a Thread
      Recipe 20.6.  Running a Code Block on Many Objects Simultaneously
      Recipe 20.7.  Limiting Multithreading with a Thread Pool
      Recipe 20.8.  Driving an External Process with popen
      Recipe 20.9.  Capturing the Output and Error Streams from a Unix Shell Command
      Recipe 20.10.  Controlling a Process on Another Machine
      Recipe 20.11.  Avoiding Deadlock
        Chapter 21.  User Interface
      Recipe 21.1. 
      Recipe 21.2.  Getting Input One Line at a Time
      Recipe 21.3.  Getting Input One Character at a Time
      Recipe 21.4.  Parsing Command-Line Arguments
      Recipe 21.5.  Testing Whether a Program Is Running Interactively
      Recipe 21.6.  Setting Up and Tearing Down a Curses Program
      Recipe 21.7.  Clearing the Screen
      Recipe 21.8.  Determining Terminal Size
      Recipe 21.9.  Changing Text Color
      Recipe 21.10.  Reading a Password
      Recipe 21.11.  Allowing Input Editing with Readline
      Recipe 21.12.  Making Your Keyboard Lights Blink
      Recipe 21.13.  Creating a GUI Application with Tk
      Recipe 21.14.  Creating a GUI Application with wxRuby
      Recipe 21.15.  Creating a GUI Application with Ruby/GTK
      Recipe 21.16.  Creating a Mac OS X Application with RubyCocoa
      Recipe 21.17.  Using AppleScript to Get User Input
        Chapter 22.  Extending Ruby with Other Languages
      Recipe 22.1.  Writing a C Extension for Ruby
      Recipe 22.2.  Using a C Library from Ruby
      Recipe 22.3.  Calling a C Library Through SWIG
      Recipe 22.4.  Writing Inline C in Your Ruby Code
      Recipe 22.5.  Using Java Libraries with JRuby
        Chapter 23.  System Administration
      Recipe 23.1.  Scripting an External Program
      Recipe 23.2.  Managing Windows Services
      Recipe 23.3.  Running Code as Another User
      Recipe 23.4.  Running Periodic Tasks Without cron or at
      Recipe 23.5.  Deleting Files That Match a Regular Expression
      Recipe 23.6.  Renaming Files in Bulk
      Recipe 23.7.  Finding Duplicate Files
      Recipe 23.8.  Automating Backups
      Recipe 23.9.  Normalizing Ownership and Permissions in User Directories
      Recipe 23.10.  Killing All Processes for a Given User
   About the Authors