Ruby Cookbook ™
Total Page:16
File Type:pdf, Size:1020Kb
www.allitebooks.com www.allitebooks.com ,TITLE.21720 Page i Friday, July 7, 2006 4:42 PM Ruby Cookbook ™ www.allitebooks.com ,TITLE.21720 Page ii Friday, July 7, 2006 4:42 PM Other resources from O’Reilly Related titles Ajax Hacks™ Rails Cookbook™ Ajax Design Patterns Ruby on Rails: Up and Head Rush Ajax Running oreilly.com oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples. oreillynet.com is the essential portal for developers interested in open and emerging technologies, including new platforms, pro- gramming languages, and operating systems. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit con- ferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online refer- ence library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim- ply flip to the page you need. Try it today for free. www.allitebooks.com ,TITLE.21720 Page iii Friday, July 7, 2006 4:42 PM Ruby Cookbook™ Lucas Carlson and Leonard Richardson Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo www.allitebooks.com ,COPYRIGHT.21583 Page iv Friday, July 7, 2006 4:42 PM Ruby Cookbook by Lucas Carlson and Leonard Richardson Copyright © 2006 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editor: Mike Loukides Cover Designer: Karen Montgomery Production Editor: Colleen Gorman Interior Designer: David Futato Proofreader: Colleen Gorman Illustrators: Robert Romano and Jessamyn Read Indexer: Johnna VanHoose Dinse Printing History: July 2006: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Cookbook series designations, Ruby Cookbook, the image of a side-striped jackal, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 0-596-52369-6 [M] www.allitebooks.com ,DEDICATION.6852 Page v Tuesday, June 27, 2006 11:12 AM For Tess, who sat by me the whole time. For John and Rael, the best programmers I know. —Lucas Carlson For Sumana. —Leonard Richardson www.allitebooks.com ,DEDICATION.6852 Page vi Tuesday, June 27, 2006 11:12 AM www.allitebooks.com Table of Contents Preface . xix 1. Strings . 1 1.1 Building a String from Parts 4 1.2 Substituting Variables into Strings 6 1.3 Substituting Variables into an Existing String 8 1.4 Reversing a String by Words or Characters 10 1.5 Representing Unprintable Characters 11 1.6 Converting Between Characters and Values 14 1.7 Converting Between Strings and Symbols 14 1.8 Processing a String One Character at a Time 16 1.9 Processing a String One Word at a Time 17 1.10 Changing the Case of a String 19 1.11 Managing Whitespace 21 1.12 Testing Whether an Object Is String-Like 22 1.13 Getting the Parts of a String You Want 23 1.14 Handling International Encodings 24 1.15 Word-Wrapping Lines of Text 26 1.16 Generating a Succession of Strings 28 1.17 Matching Strings with Regular Expressions 30 1.18 Replacing Multiple Patterns in a Single Pass 32 1.19 Validating an Email Address 33 1.20 Classifying Text with a Bayesian Analyzer 37 2. Numbers . 39 2.1 Parsing a Number from a String 40 2.2 Comparing Floating-Point Numbers 43 vii www.allitebooks.com 2.3 Representing Numbers to Arbitrary Precision 45 2.4 Representing Rational Numbers 48 2.5 Generating Random Numbers 50 2.6 Converting Between Numeric Bases 52 2.7 Taking Logarithms 53 2.8 Finding Mean, Median, and Mode 55 2.9 Converting Between Degrees and Radians 58 2.10 Multiplying Matrices 60 2.11 Solving a System of Linear Equations 64 2.12 Using Complex Numbers 67 2.13 Simulating a Subclass of Fixnum 69 2.14 Doing Math with Roman Numbers 73 2.15 Generating a Sequence of Numbers 78 2.16 Generating Prime Numbers 81 2.17 Checking a Credit Card Checksum 85 3. Date and Time . 87 3.1 Finding Today’s Date 90 3.2 Parsing Dates, Precisely or Fuzzily 93 3.3 Printing a Date 96 3.4 Iterating Over Dates 100 3.5 Doing Date Arithmetic 102 3.6 Counting the Days Since an Arbitrary Date 104 3.7 Converting Between Time Zones 106 3.8 Checking Whether Daylight Saving Time Is in Effect 109 3.9 Converting Between Time and DateTime Objects 110 3.10 Finding the Day of the Week 113 3.11 Handling Commercial Dates 115 3.12 Running a Code Block Periodically116 3.13 Waiting a Certain Amount of Time 118 3.14 Adding a Timeout to a Long-Running Operation 121 4. Arrays . 123 4.1 Iterating Over an Array125 4.2 Rearranging Values Without Using Temporary Variables 129 4.3 Stripping Duplicate Elements from an Array130 4.4 Reversing an Array132 4.5 Sorting an Array132 4.6 Ignoring Case When Sorting Strings 134 viii | Table of Contents www.allitebooks.com 4.7 Making Sure a Sorted Array Stays Sorted 135 4.8 Summing the Items of an Array140 4.9 Sorting an Array by Frequency of Appearance 141 4.10 Shuffling an Array143 4.11 Getting the N Smallest Items of an Array145 4.12 Building Up a Hash Using Injection 147 4.13 Extracting Portions of Arrays 149 4.14 Computing Set Operations on Arrays 152 4.15 Partitioning or Classifying a Set 155 5. Hashes . 159 5.1 Using Symbols as Hash Keys 161 5.2 Creating a Hash with a Default Value 162 5.3 Adding Elements to a Hash 164 5.4 Removing Elements from a Hash 166 5.5 Using an Array or Other Modifiable Object as a Hash Key 168 5.6 Keeping Multiple Values for the Same Hash Key170 5.7 Iterating Over a Hash 171 5.8 Iterating Over a Hash in Insertion Order 174 5.9 Printing a Hash 175 5.10 Inverting a Hash 177 5.11 Choosing Randomly from a Weighted List 179 5.12 Building a Histogram 181 5.13 Remapping the Keys and Values of a Hash 183 5.14 Extracting Portions of Hashes 184 5.15 Searching a Hash with Regular Expressions 185 6. Files and Directories . 187 6.1 Checking to See If a File Exists 190 6.2 Checking Your Access to a File 191 6.3 Changing the Permissions on a File 193 6.4 Seeing When a File Was Last Used 196 6.5 Listing a Directory198 6.6 Reading the Contents of a File 201 6.7 Writing to a File 204 6.8 Writing to a Temporary File 206 6.9 Picking a Random Line from a File 207 6.10 Comparing Two Files 209 6.11 Performing Random Access on “Read-Once” Input Streams 212 Table of Contents | ix 6.12 Walking a Directory Tree 214 6.13 Locking a File 217 6.14 Backing Up to Versioned Filenames 220 6.15 Pretending a String Is a File 222 6.16 Redirecting Standard Input or Output 225 6.17 Processing a Binary File 227 6.18 Deleting a File 231 6.19 Truncating a File 232 6.20 Finding the Files You Want 233 6.21 Finding and Changing the Current Working Directory235 7. Code Blocks and Iteration . 237 7.1 Creating and Invoking a Block 240 7.2 Writing a Method That Accepts a Block 241 7.3 Binding a Block Argument to a Variable 244 7.4 Blocks as Closures: Using Outside Variables Within a Code Block 246 7.5 Writing an Iterator Over a Data Structure 247 7.6 Changing the Way an Object Iterates 250 7.7 Writing Block Methods That Classify or Collect 253 7.8 Stopping an Iteration 254 7.9 Looping Through Multiple Iterables in Parallel 256 7.10 Hiding Setup and Cleanup in a Block Method 260 7.11 Coupling Systems Loosely with Callbacks 262 8. Objects and Classes . 267 8.1 Managing Instance Data 269 8.2 Managing Class Data 272 8.3 Checking Class or Module Membership 275 8.4 Writing an Inherited Class 277 8.5 Overloading Methods 279 8.6 Validating and Modifying Attribute Values 281 8.7 Defining a Virtual Attribute 283 8.8 Delegating Method Calls to Another Object 284 8.9 Converting and Coercing Objects to Different Types 287 8.10 Getting a Human-Readable Printout of AnyObject 291 8.11 Accepting or Passing a Variable Number of Arguments 293 8.12 Simulating Keyword Arguments 295 8.13 Calling a Superclass’s Method 297 8.14 Creating an Abstract Method 299 x | Table of Contents 8.15 Freezing an Object to Prevent Changes 302 8.16 Making a Copy of an Object 304 8.17 Declaring Constants 307 8.18 Implementing Class and Singleton Methods 309 8.19 Controlling Access by Making Methods Private 311 9.