Ruby Cookbook, Second Edition, by Lucas Carlson and Leonard Richardson
Total Page:16
File Type:pdf, Size:1020Kb
Updated2nd for Edition Ruby 2.1 Ruby Cookbook SECOND EDITION Why spend time on coding problems that others have already solved when Programmersdon’t “ Cookbook Ruby you could be making real progress on your Ruby project? This updated livebylanguagesyn- cookbook provides more than 350 recipes for solving common problems, on topics ranging from basic data structures, classes, and objects, to web taxalone,butbyevery development, distributed programming, and multithreading. lineofconcretecode Revised for Ruby 2.1, each recipe includes a discussion on why and how theywrite.Tothatend, the solution works. You’ll find recipes suitable for all skill levels, from thisbookisfilledwith Ruby newbies to experts who need an occasional reference. With Ruby practicalrecipes,tips, Cookbook, you’ll not only save time, but keep your brain percolating with new ideas as well. knowledge,andwisdom. Ihopeitleadsreaders Recipes cover: tothenextstepofRuby ■ Data structures including strings, numbers, date and time, programming.” arrays, hashes, files, and directories —Yukihiro (Matz) Matsumoto ■ Using Ruby’s code blocks, also known as closures Creator of Ruby ■ 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 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 http://www.lucascarlson.net/. Richardson Leonard Richardson has been programming since he was eight years old. Carlson & Recently, the quality of his code has improved somewhat. He is responsible for programming language libraries, including Rubyful Soup. He maintains a website Cookbook at http://www.crummy.com/. RECIPES FOR OBJECT-ORIENTED SCRIPTING PROGRAMMING LANGUAGES/RUBY Twitter: @oreillymedia facebook.com/oreilly US $49.99 CAN $57.99 ISBN: 978-1-449-37371-9 Lucas Carlson & Leonard Richardson www.it-ebooks.info Updated2nd for Edition Ruby 2.1 Ruby Cookbook SECOND EDITION Why spend time on coding problems that others have already solved when Programmersdon’t “ Cookbook Ruby you could be making real progress on your Ruby project? This updated livebylanguagesyn- cookbook provides more than 350 recipes for solving common problems, on topics ranging from basic data structures, classes, and objects, to web taxalone,butbyevery development, distributed programming, and multithreading. lineofconcretecode Revised for Ruby 2.1, each recipe includes a discussion on why and how theywrite.Tothatend, the solution works. You’ll find recipes suitable for all skill levels, from thisbookisfilledwith Ruby newbies to experts who need an occasional reference. With Ruby practicalrecipes,tips, Cookbook, you’ll not only save time, but keep your brain percolating with new ideas as well. knowledge,andwisdom. Ihopeitleadsreaders Recipes cover: tothenextstepofRuby ■ Data structures including strings, numbers, date and time, programming.” arrays, hashes, files, and directories —Yukihiro (Matz) Matsumoto ■ Using Ruby’s code blocks, also known as closures Creator of Ruby ■ 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 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 http://www.lucascarlson.net/. Richardson Leonard Richardson has been programming since he was eight years old. Carlson & Recently, the quality of his code has improved somewhat. He is responsible for programming language libraries, including Rubyful Soup. He maintains a website Cookbook at http://www.crummy.com/. RECIPES FOR OBJECT-ORIENTED SCRIPTING PROGRAMMING LANGUAGES/RUBY Twitter: @oreillymedia facebook.com/oreilly US $49.99 CAN $57.99 ISBN: 978-1-449-37371-9 Lucas Carlson & Leonard Richardson www.it-ebooks.info SECOND EDITION Ruby Cookbook Lucas Carlson and Leonard Richardson www.it-ebooks.info 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 (http://safaribooksonline.com). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected]. Editors: Brian Anderson and Allyson MacDonald Interior Designer: David Futato Production Editor: Matthew Hacker Cover Designer: Ellie Volckhausen Proofreader: Rachel Monaghan Illustrator: Rebecca Demarest Indexer: Angela Howard July 2006: First Edition March 2015: Second Edition Revision History for the Second Edition 2015-03-10: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781449373719 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] www.it-ebooks.info 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 www.it-ebooks.info www.it-ebooks.info Table of Contents Preface. xvii 1. 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 9 1.3 Syntax Changes 11 1.4 Keyword Arguments 14 1.5 Performance Enhancements 15 1.6 Refinements 16 1.7 Debugging with DTrace and TracePoint 17 1.8 Module Prepending 19 1.9 New Methods 21 1.10 New Classes 23 1.11 New Standard Libraries 26 1.12 What’s Next? 27 2. Strings. 29 2.1 Building a String from Parts 33 2.2 Substituting Variables into Strings 35 2.3 Substituting Variables into an Existing String 37 2.4 Reversing a String by Words or Characters 39 2.5 Representing Unprintable Characters 40 2.6 Converting Between Characters and Values 43 2.7 Converting Between Strings and Symbols 44 2.8 Processing a String One Character at a Time 45 2.9 Processing a String One Word at a Time 47 2.10 Changing the Case of a String 49 2.11 Managing Whitespace 50 v www.it-ebooks.info 2.12 Testing Whether an Object Is String-Like 52 2.13 Getting the Parts of a String You Want 53 2.14 Word-Wrapping Lines of Text 54 2.15 Generating a Succession of Strings 56 2.16 Matching Strings with Regular Expressions 59 2.17 Replacing Multiple Patterns in a Single Pass 61 2.18 Validating an Email Address 63 2.19 Classifying Text with a Bayesian Analyzer 66 3. Numbers. 69 3.1 Parsing a Number from a String 70 3.2 Comparing Floating-Point Numbers 73 3.3 Representing Numbers to Arbitrary Precision 76 3.4 Representing Rational Numbers 79 3.5 Generating Random Numbers 80 3.6 Converting Between Numeric Bases 82 3.7 Taking Logarithms 83 3.8 Finding Mean, Median, and Mode 86 3.9 Converting Between Degrees and Radians 89 3.10 Multiplying Matrices 90 3.11 Solving a System of Linear Equations 94 3.12 Using Complex Numbers 97 3.13 Simulating a Subclass of Fixnum 99 3.14 Doing Math with Roman Numbers 103 3.15 Generating a Sequence of Numbers 109 3.16 Generating Prime Numbers 112 3.17 Checking a Credit Card Checksum 116 4. Date and Time. 119 4.1 Finding Today’s Date 122 4.2 Parsing Dates, Precisely or Fuzzily 126 4.3 Printing a Date 129 4.4 Iterating Over Dates 134 4.5 Doing Date Arithmetic 135 4.6 Counting the Days Since an Arbitrary Date 138 4.7 Converting Between Time Zones 140 4.8 Checking Whether Daylight Saving Time Is in Effect 142 4.9 Converting Between Time and DateTime Objects 144 4.10 Finding the Day of the Week 147 4.11 Handling Commercial Dates 149 4.12 Running a Code Block Periodically 150 4.13 Waiting a Certain Amount of Time 152 vi | Table of Contents www.it-ebooks.info 4.14 Adding a Timeout to a Long-Running Operation 155 5. Arrays. 157 5.1 Iterating Over an Array 159 5.2 Rearranging Values Without Using Temporary Variables 163 5.3 Stripping Duplicate Elements from an Array 165 5.4 Reversing an Array 166 5.5 Sorting an Array 167 5.6 Ignoring Case When Sorting Strings 169 5.7 Making Sure a Sorted Array Stays Sorted 170 5.8 Summing the Items of an Array 175 5.9 Sorting an Array by Frequency of Appearance 177 5.10 Shuffling an Array 179 5.11 Getting the N Smallest Items of an Array 180 5.12 Building a Hash from an Array 183 5.13 Extracting Portions of Arrays 185 5.14 Computing Set Operations on Arrays 188 5.15 Partitioning or Classifying a Set 191 6.