Ruby_Cookbook_-_2nd.pdf - 1 on 2 i t i by Ed Ru d for 2 n te d Up da Ruby Cookbook Recipes cover \u25a0\u25a0 Data structures including strings numbers date

Ruby_Cookbook_-_2nd.pdf - 1 on 2 i t i by Ed Ru d for 2 n...

This preview shows page 1 out of 990 pages.

Unformatted text preview: 1 on 2. i t i by Ed Ru d for 2 n te d Up da Ruby Cookbook Recipes cover: ■■ Data structures including strings, numbers, date and time, arrays, hashes, files, and directories ■■ Using Ruby’s code blocks, also known as closures ■■ OOP features such as classes, methods, objects, and modules ■■ XML and HTML, databases and persistence, and graphics and other formats ■■ Web development with Rails and Sinatra ■■ Internet services, web services, and distributed programming ■■ Software testing, debugging, packaging, and distributing ■■ Multitasking, multithreading, and extending Ruby with other languages tax alone, but by every line of concrete code they write. To that end, this book is filled with practical recipes, tips, knowledge, and wisdom. I hope it leads readers to the next step of Ruby programming. ” —Yukihiro (Matz) Matsumoto Creator of Ruby Lucas Carlson founded AppFog, a PaaS that leverages the open source Cloud Foundry project. A professional developer for 20 years, he specializes in Ruby on Rails development. Lucas has written Programming for PaaS and Ruby Cookbook, First Edition (both O’Reilly). He maintains a website at . Leonard Richardson has been programming since he was eight years old. Recently, the quality of his code has improved somewhat. He is responsible for programming language libraries, including Rubyful Soup. He maintains a website at . PROGR AMMING L ANGUAGES/RUBY US $49.99 CAN $57.99 ISBN: 978-1-449-37371-9 Twitter: @oreillymedia facebook.com/oreilly Ruby Carlson & Richardson Revised for Ruby 2.1, each recipe includes a discussion on why and how the solution works. You’ll find recipes suitable for all skill levels, from Ruby newbies to experts who need an occasional reference. With Ruby Cookbook, you’ll not only save time, but keep your brain percolating with new ideas as well. “Programmers live by languagedon’tsyn- SECOND EDITION Ruby Cookbook 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. RECIPES FOR OBJEC T-ORIENTED SCRIPTING Cookbook Lucas Carlson & Leonard Richardson 1 on 2. i t i by Ed Ru d for 2 n te d Up da Ruby Cookbook Recipes cover: ■■ Data structures including strings, numbers, date and time, arrays, hashes, files, and directories ■■ Using Ruby’s code blocks, also known as closures ■■ OOP features such as classes, methods, objects, and modules ■■ XML and HTML, databases and persistence, and graphics and other formats ■■ Web development with Rails and Sinatra ■■ Internet services, web services, and distributed programming ■■ Software testing, debugging, packaging, and distributing ■■ Multitasking, multithreading, and extending Ruby with other languages tax alone, but by every line of concrete code they write. To that end, this book is filled with practical recipes, tips, knowledge, and wisdom. I hope it leads readers to the next step of Ruby programming. ” —Yukihiro (Matz) Matsumoto Creator of Ruby Lucas Carlson founded AppFog, a PaaS that leverages the open source Cloud Foundry project. A professional developer for 20 years, he specializes in Ruby on Rails development. Lucas has written Programming for PaaS and Ruby Cookbook, First Edition (both O’Reilly). He maintains a website at . Leonard Richardson has been programming since he was eight years old. Recently, the quality of his code has improved somewhat. He is responsible for programming language libraries, including Rubyful Soup. He maintains a website at . PROGR AMMING L ANGUAGES/RUBY US $49.99 CAN $57.99 ISBN: 978-1-449-37371-9 Twitter: @oreillymedia facebook.com/oreilly Ruby Carlson & Richardson Revised for Ruby 2.1, each recipe includes a discussion on why and how the solution works. You’ll find recipes suitable for all skill levels, from Ruby newbies to experts who need an occasional reference. With Ruby Cookbook, you’ll not only save time, but keep your brain percolating with new ideas as well. “Programmers live by languagedon’tsyn- SECOND EDITION Ruby Cookbook 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. RECIPES FOR OBJEC T-ORIENTED SCRIPTING Cookbook Lucas Carlson & Leonard Richardson SECOND EDITION Ruby Cookbook Lucas Carlson and Leonard Richardson Ruby Cookbook by Lucas Carlson and Leonard Richardson Copyright © 2015 Lucas Carlson and Leonard Richardson. 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 ( ). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected] Editors: Brian Anderson and Allyson MacDonald Production Editor: Matthew Hacker Proofreader: Rachel Monaghan Indexer: Angela Howard July 2006: March 2015: Interior Designer: David Futato Cover Designer: Ellie Volckhausen Illustrator: Rebecca Demarest First Edition Second Edition Revision History for the Second Edition 2015-03-10: First Release See for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Ruby Cookbook, the cover image of a side-striped jackal, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-449-37371-9 [M] For Yoscelina, my muse and inspiration for everything great I have ever accomplished. For Hugh and Valentina, the most incredible miracles ever. For Tess, who sat by me the whole time. —Lucas Carlson For Sumana. —Leonard Richardson Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii 1. Ruby 2.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 What’s Different Between Ruby 1.8 and 2.1? 1.2 YARV (Yet Another Ruby VM) Bytecode Interpreter 1.3 Syntax Changes 1.4 Keyword Arguments 1.5 Performance Enhancements 1.6 Refinements 1.7 Debugging with DTrace and TracePoint 1.8 Module Prepending 1.9 New Methods 1.10 New Classes 1.11 New Standard Libraries 1.12 What’s Next? 2 9 11 14 15 16 17 19 21 23 26 27 2. Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.1 Building a String from Parts 2.2 Substituting Variables into Strings 2.3 Substituting Variables into an Existing String 2.4 Reversing a String by Words or Characters 2.5 Representing Unprintable Characters 2.6 Converting Between Characters and Values 2.7 Converting Between Strings and Symbols 2.8 Processing a String One Character at a Time 2.9 Processing a String One Word at a Time 2.10 Changing the Case of a String 2.11 Managing Whitespace 33 35 37 39 40 43 44 45 47 49 50 v 2.12 Testing Whether an Object Is String-Like 2.13 Getting the Parts of a String You Want 2.14 Word-Wrapping Lines of Text 2.15 Generating a Succession of Strings 2.16 Matching Strings with Regular Expressions 2.17 Replacing Multiple Patterns in a Single Pass 2.18 Validating an Email Address 2.19 Classifying Text with a Bayesian Analyzer 52 53 54 56 59 61 63 66 3. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 3.1 Parsing a Number from a String 3.2 Comparing Floating-Point Numbers 3.3 Representing Numbers to Arbitrary Precision 3.4 Representing Rational Numbers 3.5 Generating Random Numbers 3.6 Converting Between Numeric Bases 3.7 Taking Logarithms 3.8 Finding Mean, Median, and Mode 3.9 Converting Between Degrees and Radians 3.10 Multiplying Matrices 3.11 Solving a System of Linear Equations 3.12 Using Complex Numbers 3.13 Simulating a Subclass of Fixnum 3.14 Doing Math with Roman Numbers 3.15 Generating a Sequence of Numbers 3.16 Generating Prime Numbers 3.17 Checking a Credit Card Checksum 70 73 76 79 80 82 83 86 89 90 94 97 99 103 109 112 116 4. Date and Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 4.1 Finding Today’s Date 4.2 Parsing Dates, Precisely or Fuzzily 4.3 Printing a Date 4.4 Iterating Over Dates 4.5 Doing Date Arithmetic 4.6 Counting the Days Since an Arbitrary Date 4.7 Converting Between Time Zones 4.8 Checking Whether Daylight Saving Time Is in Effect 4.9 Converting Between Time and DateTime Objects 4.10 Finding the Day of the Week 4.11 Handling Commercial Dates 4.12 Running a Code Block Periodically 4.13 Waiting a Certain Amount of Time vi | Table of Contents 122 126 129 134 135 138 140 142 144 147 149 150 152 4.14 Adding a Timeout to a Long-Running Operation 155 5. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 5.1 Iterating Over an Array 5.2 Rearranging Values Without Using Temporary Variables 5.3 Stripping Duplicate Elements from an Array 5.4 Reversing an Array 5.5 Sorting an Array 5.6 Ignoring Case When Sorting Strings 5.7 Making Sure a Sorted Array Stays Sorted 5.8 Summing the Items of an Array 5.9 Sorting an Array by Frequency of Appearance 5.10 Shuffling an Array 5.11 Getting the N Smallest Items of an Array 5.12 Building a Hash from an Array 5.13 Extracting Portions of Arrays 5.14 Computing Set Operations on Arrays 5.15 Partitioning or Classifying a Set 159 163 165 166 167 169 170 175 177 179 180 183 185 188 191 6. Hashes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 6.1 Using Symbols as Hash Keys 6.2 Creating a Hash with a Default Value 6.3 Adding Elements to a Hash 6.4 Removing Elements from a Hash 6.5 Using an Array or Other Modifiable Object as a Hash Key 6.6 Keeping Multiple Values for the Same Hash Key 6.7 Iterating Over a Hash 6.8 Iterating Over a Hash in Insertion Order 6.9 Printing a Hash 6.10 Inverting a Hash 6.11 Choosing Randomly from a Weighted List 6.12 Building a Histogram 6.13 Remapping the Keys and Values of a Hash 6.14 Extracting Portions of Hashes 6.15 Searching a Hash with Regular Expressions 200 201 203 205 206 209 210 213 214 216 217 220 222 223 224 7. Files and Directories. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 7.1 Checking to See If a File Exists 7.2 Checking Your Access to a File 7.3 Changing the Permissions on a File 7.4 Seeing When a File Was Last Used 7.5 Listing a Directory 230 232 234 237 239 Table of Contents | vii 7.6 Reading the Contents of a File 7.7 Writing to a File 7.8 Writing to a Temporary File 7.9 Picking a Random Line from a File 7.10 Comparing Two Files 7.11 Performing Random Access on “Read-Once” Input Streams 7.12 Walking a Directory Tree 7.13 Locking a File 7.14 Backing Up to Versioned Filenames 7.15 Pretending a String Is a File 7.16 Redirecting Standard Input or Output 7.17 Processing a Binary File 7.18 Deleting a File 7.19 Truncating a File 7.20 Finding the Files You Want 7.21 Finding and Changing the Current Working Directory 242 246 247 249 250 254 256 259 262 265 268 270 274 275 277 279 8. Code Blocks and Iteration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 8.1 Creating and Invoking a Block 8.2 Writing a Method That Accepts a Block 8.3 Binding a Block Argument to a Variable 8.4 Blocks as Closures: Using Outside Variables Within a Code Block 8.5 Writing an Iterator Over a Data Structure 8.6 Changing the Way an Object Iterates 8.7 Writing Block Methods That Classify or Collect 8.8 Stopping an Iteration 8.9 Looping Through Multiple Iterables in Parallel 8.10 Hiding Setup and Cleanup in a Block Method 8.11 Coupling Systems Loosely with Callbacks 284 286 289 291 293 296 298 300 302 306 308 9. Objects and Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 9.1 Managing Instance Data 9.2 Managing Class Data 9.3 Checking Class or Module Membership 9.4 Writing an Inherited Class 9.5 Overloading Methods 9.6 Validating and Modifying Attribute Values 9.7 Defining a Virtual Attribute 9.8 Delegating Method Calls to Another Object 9.9 Converting and Coercing Objects to Different Types 9.10 Getting a Human-Readable Printout of Any Object 9.11 Accepting or Passing a Variable Number of Arguments viii | Table of Contents 316 318 321 323 326 328 330 331 334 339 341 9.12 Using Keyword Arguments 9.13 Calling a Superclass’s Method 9.14 Creating an Abstract Method 9.15 Freezing an Object to Prevent Changes 9.16 Making a Copy of an Object 9.17 Declaring Constants 9.18 Implementing Class and Singleton Methods 9.19 Controlling Access by Making Methods Private 343 345 347 350 353 356 358 360 10. Modules and Namespaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 10.1 Simulating Multiple Inheritance with Mixins 10.2 Extending Specific Objects with Modules 10.3 Mixing in Class Methods 10.4 Implementing Enumerable: Write One Method, Get 48 Free 10.5 Avoiding Naming Collisions with Namespaces 10.6 Automatically Loading Libraries as Needed 10.7 Including Namespaces 10.8 Initializing Instance Variables Defined by a Module 10.9 Automatically Initializing Mixed-in Modules 10.10 Prepending Modules 366 370 372 373 377 378 380 382 383 386 11. Reflection and Metaprogramming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 11.1 Finding an Object’s Class and Superclass 11.2 Listing an Object’s Methods 11.3 Listing Methods Unique to an Object 11.4 Getting a Reference to a Method 11.5 Fixing Bugs in Someone Else’s Class 11.6 Listening for Changes to a Class 11.7 Checking Whether an Object Has Necessary Attributes 11.8 Responding to Calls to Undefined Methods 11.9 Automatically Initializing Instance Variables 11.10 Avoiding Boilerplate Code with Metaprogramming 11.11 Metaprogramming with String Evaluations 11.12 Evaluating Code in an Earlier Context 11.13 Undefining a Method 11.14 Aliasing Methods 11.15 Doing Aspect-Oriented Programming 11.16 Enforcing Software Contracts 390 391 394 396 398 400 403 404 409 410 413 415 417 420 423 425 12. XML and HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431 12.1 Checking That XML Is Well Formed 12.2 Extracting Data from a Document’s Tree Structure 432 434 Table of Contents | ix 12.3 Extracting Data While Parsing a Document 12.4 Navigating a Document with XPath 12.5 Converting an XML Document into a Hash 12.6 Validating an XML Document 12.7 Substituting XML Entities 12.8 Creating and Modifying XML Documents 12.9 Compressing Whitespace in an XML Document 12.10 Guessing a Document’s Encoding 12.11 Converting from One Encoding to Another 12.12 Extracting All the URLs from an HTML Document 12.13 Transforming Plain Text to HTML 12.14 Converting HTML Documents from the Web into Text 12.15 Creating a Simple Feed Aggregator 436 438 441 444 445 448 452 453 454 456 459 460 463 13. Graphics and Other File Formats. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469 13.1 Thumbnailing Images 13.2 Adding Text to an Image 13.3 Converting One Image Format to Another 13.4 Graphing Data 13.5 Adding Graphical Context with Sparklines 13.6 Symmetrically Encrypting Data 13.7 Parsing Comma-Separated Data 13.8 Parsing Not-Quite-Comma-Separated Data 13.9 Generating and Parsing Excel Spreadsheets 13.10 Compressing and Archiving Files with Gzip and Tar 13.11 Reading and Writing ZIP Files 13.12 Reading and Writing Configuration Files 13.13 Generating PDF Files 13.14 Representing Data as MIDI Music 470 473 476 479 482 485 487 489 490 492 495 497 499 503 14. Databases and Persistence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507 14.1 Serializing Data with YAML 14.2 Serializing Data with Marshal 14.3 Persisting Objects with Madeleine 14.4 Indexing Unstructured Text with SimpleSearch 14.5 Indexing Structured Text with Ferret 14.6 Using Berkeley DB Databases 14.7 Controlling MySQL on Unix 14.8 Finding the Number of Rows Returned by a Query 14.9 Talking Directly to a MySQL Database 14.10 Talking Directly to a PostgreSQL Database 14.11 Using Object Relational Mapping with ActiveRecord x | Table of Contents 511 514 515 518 520 524 525 526 528 531 534 14.12 Building Queries Programmatically 14.13 Validating Data with ActiveRecord 14.14 Preventing SQL Injection Attacks 14.15 Using Transactions in ActiveRecord 14.16 Adding Hooks to Table Events 14.17 Adding Taggability with a Database Mixin 538 542 544 547 549 551 15. Internet Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555 15.1 Grabbing the Contents of a Web Page 15.2 Making an HTTPS Web Request 15.3 Customizing HTTP Request Headers 15.4 Performing DNS Queries 15.5 Sending Mail 15.6 Reading Mail with IMAP 15.7 Reading Mail with POP3 15.8 Being an FTP Client 15.9 Being a Telnet Client 15.10 Being an SSH Client 15.11 Copying a File to Another Machine 15.12 Being a BitTorrent Client 15.13 Pinging a Machine 15.14 Writing an Internet Server 15.15 Parsing URLs 15.16 Writing a CGI Script 15.17 Setting Cookies and Other HTTP Response Headers 15.18 Handling File Uploads via CGI 15.19 Running Servlets with WEBrick 15.20 Creating a Real-World HTTP Client 556 559 561 563 565 569 574 577 579 583 585 587 588 589 592 595 598 600 603 609 16. Web Development: Ruby on Rails. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613 16.1 Writing a Simple Rails Application to Show System Status 16.2 Passing Data from the Controller to the View 16.3 Creating a Layout for Your Header and Footer 16.4 Redirecting to a Different Location 16.5 Displaying Templates with Render 16.6 Integrating a Database with Your Rails Application 16.7 Understanding Pluralization Rules 16.8 Creating a Login System 16.9 Storing Hashed User Passwords in the Database 16.10 Escaping HTML and JavaScript for Display 16.11 Setting and Retrieving Session Information 16.12 Setting and Retrieving Cookies 616 619 621 624 626 629 633 636 640 642 643 645 Table of Contents | xi 16.13 Extracting Code into Helper Functions 16.14 Refactoring the View into Partial Snippets of Views 16.15 Adding Dynamic Effects with script.aculo.us 16.16 Generating Forms for Manipulating Model Objects 16.17 Creating an Ajax Form 16.18 Exposing Web Services on Your Website 16.19 Sending Mail with Rails 16.20 Automatically Sending Error Messages to Your Email 16.21 Documenting Your Websit...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture