Do you want to push Ruby to its limits? The Ruby Cookbook is the most comprehensive problem-solving guide to today's hottest programming 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.
Chapter 1 Strings
Building a String from Parts
Substituting Variables into Strings
Substituting Variables into an Existing String
Reversing a String by Words or Characters
Representing Unprintable Characters
Converting Between Characters and Values
Converting Between Strings and Symbols
Processing a String One Character at a Time
Processing a String One Word at a Time
Changing the Case of a String
Managing Whitespace
Testing Whether an Object Is String-Like
Getting the Parts of a String You Want
Handling International Encodings
Word-Wrapping Lines of Text
Generating a Succession of Strings
Matching Strings with Regular Expressions
Replacing Multiple Patterns in a Single Pass
Validating an Email Address
Classifying Text with a Bayesian Analyzer
Chapter 2 Numbers
Parsing a Number from a String
Comparing Floating-Point Numbers
Representing Numbers to Arbitrary Precision
Representing Rational Numbers
Generating Random Numbers
Converting Between Numeric Bases
Taking Logarithms
Finding Mean, Median, and Mode
Converting Between Degrees and Radians
Multiplying Matrices
Solving a System of Linear Equations
Using Complex Numbers
Simulating a Subclass of Fixnum
Doing Math with Roman Numbers
Generating a Sequence of Numbers
Generating Prime Numbers
Checking a Credit Card Checksum
Chapter 3 Date and Time
Finding Today's Date
Parsing Dates, Precisely or Fuzzily
Printing a Date
Iterating Over Dates
Doing Date Arithmetic
Counting the Days Since an Arbitrary Date
Converting Between Time Zones
Checking Whether Daylight Saving Time Is in Effect
Converting Between Time and DateTime Objects
Finding the Day of the Week
Handling Commercial Dates
Running a Code Block Periodically
Waiting a Certain Amount of Time
Adding a Timeout to a Long-Running Operation
Chapter 4 Arrays
Iterating Over an Array
Rearranging Values Without Using Temporary Variables
Stripping Duplicate Elements from an Array
Reversing an Array
Sorting an Array
Ignoring Case When Sorting Strings
Making Sure a Sorted Array Stays Sorted
Summing the Items of an Array
Sorting an Array by Frequency of Appearance
Shuffling an Array
Getting the N Smallest Items of an Array
Building Up a Hash Using Injection
Extracting Portions of Arrays
Computing Set Operations on Arrays
Partitioning or Classifying a Set
Chapter 5 Hashes
Using Symbols as Hash Keys
Creating a Hash with a Default Value
Adding Elements to a Hash
Removing Elements from a Hash
Using an Array or Other Modifiable Object as a Hash Key
Keeping Multiple Values for the Same Hash Key
Iterating Over a Hash
Iterating Over a Hash in Insertion Order
Printing a Hash
Inverting a Hash
Choosing Randomly from a Weighted List
Building a Histogram
Remapping the Keys and Values of a Hash
Extracting Portions of Hashes
Searching a Hash with Regular Expressions
Chapter 6 Files and Directories
Checking to See If a File Exists
Checking Your Access to a File
Changing the Permissions on a File
Seeing When a File Was Last Used Problem
Listing a Directory
Reading the Contents of a File
Writing to a File
Writing to a Temporary File
Picking a Random Line from a File
Comparing Two Files
Performing Random Access on "Read-Once" Input Streams
Walking a Directory Tree
Locking a File
Backing Up to Versioned Filenames
Pretending a String Is a File
Redirecting Standard Input or Output
Processing a Binary File
Deleting a File
Truncating a File
Finding the Files You Want
Finding and Changing the Current Working Directory
Chapter 7 Code Blocks and Iteration
Creating and Invoking a Block
Writing a Method That Accepts a Block
Binding a Block Argument to a Variable
Blocks as Closures: Using Outside Variables Within a Code Block
Writing an Iterator Over a Data Structure
Changing the Way an Object Iterates
Writing Block Methods That Classify or Collect
Stopping an Iteration
Looping Through Multiple Iterables in Parallel
Hiding Setup and Cleanup in a Block Method
Coupling Systems Loosely with Callbacks
Chapter 8 Objects and Classes
Managing Instance Data
Managing Class Data
Checking Class or Module Membership
Writing an Inherited Class
Overloading Methods
Validating and Modifying Attribute Values
Defining a Virtual Attribute
Delegating Method Calls to Another Object
Converting and Coercing Objects to Different Types
Getting a Human-Readable Printout of Any Object
Accepting or Passing a Variable Number of Arguments
Simulating Keyword Arguments
Calling a Superclass's Method
Creating an Abstract Method
Freezing an Object to Prevent Changes
Making a Copy of an Object
Declaring Constants
Implementing Class and Singleton Methods
Controlling Access by Making Methods Private
Chapter 9 Modules and Namespaces
Simulating Multiple Inheritance with Mixins
Extending Specific Objects with Modules
Mixing in Class Methods
Implementing Enumerable: Write One Method, Get 22 Free
Avoiding Naming Collisions with Namespaces
Automatically Loading Libraries as Needed
Including Namespaces
Initializing Instance Variables Defined by a Module
Automatically Initializing Mixed-In Modules
Chapter 10 Reflection and Metaprogramming
Finding an Object's Class and Superclass
Listing an Object's Methods
Listing Methods Unique to an Object
Getting a Reference to a Method
Fixing Bugs in Someone Else's Class
Listening for Changes to a Class
Checking Whether an Object Has Necessary Attributes
Responding to Calls to Undefined Methods
Automatically Initializing Instance Variables
Avoiding Boilerplate Code with Metaprogramming
Metaprogramming with String Evaluations
Evaluating Code in an Earlier Context
Undefining a Method
Aliasing Methods
Doing Aspect-Oriented Programming
Enforcing Software Contracts
Chapter 11 XML and HTML
Checking XML Well-Formedness
Extracting Data from a Document's Tree Structure
Extracting Data While Parsing a Document
Navigating a Document with XPath
Parsing Invalid Markup
Converting an XML Document into a Hash
Validating an XML Document
Substituting XML Entities
Creating and Modifying XML Documents
Compressing Whitespace in an XML Document
Guessing a Document's Encoding
Converting from One Encoding to Another
Extracting All the URLs from an HTML Document
Transforming Plain Text to HTML
Converting HTML Documents from the Web into Text
A Simple Feed Aggregator
Chapter 12 Graphics and Other File Formats
Thumbnailing Images
Adding Text to an Image
Converting One Image Format to Another
Graphing Data
Adding Graphical Context with Sparklines
Strongly Encrypting Data
Parsing Comma-Separated Data
Parsing Not-Quite-Comma-Separated Data
Generating and Parsing Excel Spreadsheets
Compressing and Archiving Files with Gzip and Tar
Reading and Writing ZIP Files
Reading and Writing Configuration Files
Generating PDF Files
Representing Data as MIDI Music
Chapter 13 Databases and Persistence
Serializing Data with YAML
Serializing Data with Marshal
Persisting Objects with Madeleine
Indexing Unstructured Text with SimpleSearch
Indexing Structured Text with Ferret
Using Berkeley DB Databases
Controlling MySQL on Unix
Finding the Number of Rows Returned by a Query
Talking Directly to a MySQL Database
Talking Directly to a PostgreSQL Database
Using Object Relational Mapping with ActiveRecord
Using Object Relational Mapping with Og
Building Queries Programmatically
Validating Data with ActiveRecord
Preventing SQL Injection Attacks
Using Transactions in ActiveRecord
Adding Hooks to Table Events
Adding Taggability with a Database Mixin
Chapter 14 Internet Services
Grabbing the Contents of a Web Page
Making an HTTPS Web Request
Customizing HTTP Request Headers
Performing DNS Queries
Sending Mail
Reading Mail with IMAP
Reading Mail with POP3
Being an FTP Client
Being a Telnet Client
Being an SSH Client
Copying a File to Another Machine
Being a BitTorrent Client
Pinging a Machine
Writing an Internet Server
Parsing URLs
Writing a CGI Script
Setting Cookies and Other HTTP Response Headers
Handling File Uploads via CGI
Running Servlets with WEBrick
A Real-World HTTP Client
Chapter 15 Web Development: Ruby on Rails
Writing a Simple Rails Application to Show System Status
Passing Data from the Controller to the View
Creating a Layout for Your Header and Footer
Redirecting to a Different Location
Displaying Templates with Render
Integrating a Database with Your Rails Application
Understanding Pluralization Rules
Creating a Login System
Storing Hashed User Passwords in the Database
Escaping HTML and JavaScript for Display
Setting and Retrieving Session Information
Setting and Retrieving Cookies
Extracting Code into Helper Functions
Refactoring the View into Partial Snippets of Views
Adding DHTML Effects with script.aculo.us
Generating Forms for Manipulating Model Objects
Creating an Ajax Form
Exposing Web Services on Your Web Site
Sending Mail with Rails
Automatically Sending Error Messages to Your Email
Documenting Your Web Site
Unit Testing Your Web Site
Using breakpoint in Your Web Application
Chapter 16 Web Services and Distributed Programming
Searching for Books on Amazon
Finding Photos on Flickr
Writing an XML-RPC Client
Writing a SOAP Client
Writing a SOAP Server
Searching the Web with Google's SOAP Service
Using a WSDL File to Make SOAP Calls Easier
Charging a Credit Card
Finding the Cost to Ship Packages via UPS or FedEx
Sharing a Hash Between Any Number of Computers
Implementing a Distributed Queue
Creating a Shared "Whiteboard"
Securing DRb Services with Access Control Lists
Automatically Discovering DRb Services with Rinda
Proxying Objects That Can't Be Distributed
Storing Data on Distributed RAM with MemCached
Caching Expensive Results with MemCached
A Remote-Controlled Jukebox
Chapter 17 Testing, Debugging, Optimizing, and Documenting
Running Code Only in Debug Mode
Raising an Exception
Handling an Exception
Rerunning After an Exception
Adding Logging to Your Application
Creating and Understanding Tracebacks
Writing Unit Tests
Running Unit Tests
Testing Code That Uses External Resources
Using breakpoint to Inspect and Change the State of Your Application
Documenting Your Application
Profiling Your Application
Benchmarking Competing Solutions
Running Multiple Analysis Tools at Once
Who's Calling That Method? A Call Graph Analyzer
Chapter 18 Packaging and Distributing Software
Finding Libraries by Querying Gem Respositories
Installing and Using a Gem
Requiring a Specific Version of a Gem
Uninstalling a Gem
Reading Documentation for Installed Gems
Packaging Your Code as a Gem
Distributing Your Gems
Installing and Creating Standalone Packages with setup.rb
Chapter 19 Automating Tasks with Rake
Automatically Running Unit Tests
Automatically Generating Documentation
Cleaning Up Generated Files
Automatically Building a Gem
Gathering Statistics About Your Code
Publishing Your Documentation
Running Multiple Tasks in Parallel
A Generic Project Rakefile
Chapter 20 Multitasking and Multithreading
Running a Daemon Process on Unix
Creating a Windows Service
Doing Two Things at Once with Threads
Synchronizing Access to an Object
Terminating a Thread
Running a Code Block on Many Objects Simultaneously
Limiting Multithreading with a Thread Pool
Driving an External Process with popen
Capturing the Output and Error Streams from a Unix Shell Command
Controlling a Process on Another Machine
Avoiding Deadlock
Chapter 21 User Interface
Getting Input One Line at a Time
Getting Input One Character at a Time
Parsing Command-Line Arguments
Testing Whether a Program Is Running Interactively
Setting Up and Tearing Down a Curses Program
Clearing the Screen
Determining Terminal Size
Changing Text Color
Reading a Password
Allowing Input Editing with Readline
Making Your Keyboard Lights Blink
Creating a GUI Application with Tk
Creating a GUI Application with wxRuby
Creating a GUI Application with Ruby/GTK
Creating a Mac OS X Application with RubyCocoa
Using AppleScript to Get User Input
Chapter 22 Extending Ruby with Other Languages
Writing a C Extension for Ruby
Using a C Library from Ruby
Calling a C Library Through SWIG
Writing Inline C in Your Ruby Code
Using Java Libraries with JRuby
Chapter 23 System Administration
Scripting an External Program
Managing Windows Services
Running Code as Another User
Running Periodic Tasks Without cron or at
Deleting Files That Match a Regular Expression
Renaming Files in Bulk
Finding Duplicate Files
Automating Backups
Normalizing Ownership and Permissions in User Directories
Lucas Carlson is a professional Ruby programmer who specializes in Rails web development. He has authored a half dozen libraries and contributed to many others, including Rails and RedCloth. He lives in Portland, Oregon and maintains a website at http://rufy.com/.
Leonard Richardson has been programming since he was eight years old. Recently, the quality of his code has improved somewhat. He is responsible for libraries in many languages, including Rubyful Soup. A California native, he now works in New York and maintains a website at http://www.crummy.com/.
Published by acclaimed authors Lucas Carlson and Leonard Richardson, The Ruby Cookbook is both an excellent learning tool and reference manual. It is organized into 23 chapters delineating all capabilities of the object-oriented scripting language. Each chapter is broken down into numerous subcategories describing operations, tips and tricks, common problems and their solutions, and other concepts pertaining to the topic of the chapter. Finding what you are looking for is not an issue since all topics are structured seamlessly.
Unlike many other programming books I have read, this one does not cut corners and overlook the menial steps experts, such as the authors themselves, would assume the reader to know intuitively. I find this aspect to be exceedingly beneficial in learning how the language behaves and what discrepancies may present themselves as a result of coding between a number of programming languages. While reading this book and learning the language, I had never been confused as a result of missing or vague information. The writing style is captivating, concise, and understandable. I enjoyed reading this book.
What I prefer most about the manual is that it is suited for newbies as well as experts. The introductory topics include the common data structures and how they are implemented, while the later chapters specify advanced functionality and extensions to the language. I recommend this book for all of those who have had some object-oriented programming experience as well as to those who have not but are interested in learning a computing language.
1/28/2007
(0 of 1 customers found this review helpful)
5.0
A really good book
By Jeremiah
from Undisclosed
Comments about oreilly Ruby Cookbook:
This book is a must-have for any programmer just discovering Ruby. The examples are straight forward and relevant. Combine this with a good Rails book and you have just what you need to get started on a serious project.
12/20/2006
(0 of 1 customers found this review helpful)
4.0
Very Good
By Derrick Petzold
from Undisclosed
Comments about oreilly Ruby Cookbook:
This book is excellent. If it had more swing stuff I'd probably be using it exclusively.
11/30/2006
(3 of 3 customers found this review helpful)
5.0
Ruby Cookbook Review
By Brian Anderson
from Undisclosed
Comments about oreilly Ruby Cookbook:
I've looked at a couple programming "cookbooks" over the few years I've been programming, and none have ever really captured my attention. Most of them I found were lacking in useful recipes for novice programmers, or the recipes used an outdated code style or covered specific areas of a programming language. And with others, I just found it difficult to find useful tips or tricks.
The Ruby Cookbook however, provides fresh, easy to read recipes that are full of neat tips and awesome tricks. And it's all provided in an easy to read, and more importantly easy to find, format. Programmers from novice to highly experienced will find this book useful.
The book is laid out using general data types as chapters at first, then moves into more abstract topics such as code blocks and modules; databases and persistence; web services and task automation with Rake.
Start with the table of contents to learn about a specific area, or thumb your way through the index to find specific topics or that fast piece of code you need to complete your project. No matter how you use it, the Ruby Cookbook is a must have book for any Ruby or Ruby on Rails programmer.
10/3/2006
(1 of 1 customers found this review helpful)
5.0
This Book is a Gem!
By Dave Walz-Burkett
from Undisclosed
Comments about oreilly Ruby Cookbook:
Sometimes, the difference between getting a project off the ground and watching it linger on the launchpad is finding an example of how to do something in code.
Perhaps you're working on a project and you'd like to send an email using Ruby. Maybe you'd like to know how to read and write zip files or create thumbnail images from full size graphics files. Sometimes cruising through the API documentation just doesn't quite give you enough info.
The Ruby Cookbook fills the void for a portable version of a Ruby code snippet search engine. For each example, there is a Problem description, a Solution section containing one or more chunks of Ruby code and a Discussion section for follow-up. Most examples also have a See Also section for cross reference.
A huge amount of material is covered. Topics range from simple stuff like strings, numbers, hashes, arrays and objects to more challenging subjects like code blocks, reflection, metaprogramming and multithreading. It has chapters on Internet services, Web services and distributed programming, and Web development with Ruby on Rails.
I'm only just skimming the surface here, this is a big book with 873 pages. It is quite simply packed with goodies. There is something in this book for Ruby programmers at every level. The book is well written and easy to read. You can download a zip file containing all of the code samples from the O'Reilly website.
If you want to learn Ruby and Ruby on Rails, there are three books that will help you more than anything else: Programming Ruby by Dave Thomas, Agile Web Development with Rails by Dave Thomas and David Heinemeier Hansson and the Ruby Cookbook by Lucas Carlson and Leonard Richardson.
8/5/2006
(1 of 1 customers found this review helpful)
5.0
A 'must -have' book
By Satish Talim
from Undisclosed
Comments about oreilly Ruby Cookbook:
This book is a 'must-have' for all the Ruby enthusiasts. I hope they put up a .zip file of all the programs here.