Ruby Cookbook, 2nd Edition

Book description

Why spend time on coding problems that others have already solved when you could be making real progress on your Ruby project? This updated cookbook provides more than 350 recipes for solving common problems, on topics ranging from basic data structures, classes, and objects, to web development, distributed programming, and multithreading. Revised for Ruby 2.1, each recipe includes a discussion on why and how the solution works.

Publisher resources

View/Submit Errata

Table of contents

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

Product information

  • Title: Ruby Cookbook, 2nd Edition
  • Author(s):
  • Release date: March 2015
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449373719