ebook img

Ruby Cookbook: Recipes for Object-Oriented Scripting PDF

990 Pages·2016·6.73 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Ruby Cookbook: Recipes for Object-Oriented Scripting

2 U p n d d a t E e d Ruby Cookbook d f iti o r o SECOND EDITION R n Why spend time on coding problems that others have already solved when “Programmersdon’t ub y you could be making real progress on your Ruby project? This updated livebylanguagesyn- R 2. 1 cookbook provides more than 350 recipes for solving common problems, taxalone,butbyevery on topics ranging from basic data structures, classes, and objects, to web lineofconcretecode u development, distributed programming, and multithreading. theywrite.Tothatend, Revised for Ruby 2.1, each recipe includes a discussion on why and how b 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, y Cookbook, you’ll not only save time, but keep your brain percolating with knowledge,andwisdom. new ideas as well. Ihopeitleadsreaders C Recipes cover: tothenextstepofRuby ■ Data structures including strings, numbers, date and time, programming.” arrays, hashes, files, and directories o —Yukihiro (Matz) Matsumoto ■ Using Ruby’s code blocks, also known as closures Creator of Ruby o ■ OOP features such as classes, methods, objects, and modules ■ XML and HTML, databases and persistence, and graphics and k Ruby other formats b ■ Web development with Rails and Sinatra ■ Internet services, web services, and distributed programming o ■ Software testing, debugging, packaging, and distributing ■ Multitasking, multithreading, and extending Ruby with other o languages k Cookbook 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/. R Leonard Richardson has been programming since he was eight years old. icC Recently, the quality of his code has improved somewhat. He is responsible for ha ar programming language libraries, including Rubyful Soup. He maintains a website rls at http://www.crummy.com/. do sn on & RECIPES FOR OBJECT-ORIENTED SCRIPTING PROGRAMMING LANGUAGES/RUBY Twitter: @oreillymedia facebook.com/oreilly US $49.99 CAN $57.99 Lucas Carlson ISBN: 978-1-449-37371-9 & Leonard Richardson 2 U p n d d a t E e d Ruby Cookbook d f iti o r o SECOND EDITION R n Why spend time on coding problems that others have already solved when “Programmersdon’t ub y you could be making real progress on your Ruby project? This updated livebylanguagesyn- R 2. 1 cookbook provides more than 350 recipes for solving common problems, taxalone,butbyevery on topics ranging from basic data structures, classes, and objects, to web lineofconcretecode u development, distributed programming, and multithreading. theywrite.Tothatend, Revised for Ruby 2.1, each recipe includes a discussion on why and how b 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, y Cookbook, you’ll not only save time, but keep your brain percolating with knowledge,andwisdom. new ideas as well. Ihopeitleadsreaders C Recipes cover: tothenextstepofRuby ■ Data structures including strings, numbers, date and time, programming.” arrays, hashes, files, and directories o —Yukihiro (Matz) Matsumoto ■ Using Ruby’s code blocks, also known as closures Creator of Ruby o ■ OOP features such as classes, methods, objects, and modules ■ XML and HTML, databases and persistence, and graphics and k Ruby other formats b ■ Web development with Rails and Sinatra ■ Internet services, web services, and distributed programming o ■ Software testing, debugging, packaging, and distributing ■ Multitasking, multithreading, and extending Ruby with other o languages k Cookbook 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/. R Leonard Richardson has been programming since he was eight years old. icC Recently, the quality of his code has improved somewhat. He is responsible for ha ar programming language libraries, including Rubyful Soup. He maintains a website rls at http://www.crummy.com/. do sn on & RECIPES FOR OBJECT-ORIENTED SCRIPTING PROGRAMMING LANGUAGES/RUBY Twitter: @oreillymedia facebook.com/oreilly US $49.99 CAN $57.99 Lucas Carlson ISBN: 978-1-449-37371-9 & 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 (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] 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? 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 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 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. Hashes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 6.1 Using Symbols as Hash Keys 200 6.2 Creating a Hash with a Default Value 201 6.3 Adding Elements to a Hash 203 6.4 Removing Elements from a Hash 205 6.5 Using an Array or Other Modifiable Object as a Hash Key 206 6.6 Keeping Multiple Values for the Same Hash Key 209 6.7 Iterating Over a Hash 210 6.8 Iterating Over a Hash in Insertion Order 213 6.9 Printing a Hash 214 6.10 Inverting a Hash 216 6.11 Choosing Randomly from a Weighted List 217 6.12 Building a Histogram 220 6.13 Remapping the Keys and Values of a Hash 222 6.14 Extracting Portions of Hashes 223 6.15 Searching a Hash with Regular Expressions 224 7. Files and Directories. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 7.1 Checking to See If a File Exists 230 7.2 Checking Your Access to a File 232 7.3 Changing the Permissions on a File 234 7.4 Seeing When a File Was Last Used 237 7.5 Listing a Directory 239 Table of Contents | vii 7.6 Reading the Contents of a File 242 7.7 Writing to a File 246 7.8 Writing to a Temporary File 247 7.9 Picking a Random Line from a File 249 7.10 Comparing Two Files 250 7.11 Performing Random Access on “Read-Once” Input Streams 254 7.12 Walking a Directory Tree 256 7.13 Locking a File 259 7.14 Backing Up to Versioned Filenames 262 7.15 Pretending a String Is a File 265 7.16 Redirecting Standard Input or Output 268 7.17 Processing a Binary File 270 7.18 Deleting a File 274 7.19 Truncating a File 275 7.20 Finding the Files You Want 277 7.21 Finding and Changing the Current Working Directory 279 8. Code Blocks and Iteration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 8.1 Creating and Invoking a Block 284 8.2 Writing a Method That Accepts a Block 286 8.3 Binding a Block Argument to a Variable 289 8.4 Blocks as Closures: Using Outside Variables Within a Code Block 291 8.5 Writing an Iterator Over a Data Structure 293 8.6 Changing the Way an Object Iterates 296 8.7 Writing Block Methods That Classify or Collect 298 8.8 Stopping an Iteration 300 8.9 Looping Through Multiple Iterables in Parallel 302 8.10 Hiding Setup and Cleanup in a Block Method 306 8.11 Coupling Systems Loosely with Callbacks 308 9. Objects and Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 9.1 Managing Instance Data 316 9.2 Managing Class Data 318 9.3 Checking Class or Module Membership 321 9.4 Writing an Inherited Class 323 9.5 Overloading Methods 326 9.6 Validating and Modifying Attribute Values 328 9.7 Defining a Virtual Attribute 330 9.8 Delegating Method Calls to Another Object 331 9.9 Converting and Coercing Objects to Different Types 334 9.10 Getting a Human-Readable Printout of Any Object 339 9.11 Accepting or Passing a Variable Number of Arguments 341 viii | Table of Contents

Description:
2nd Edition. — Packt Publishing, 2015. — 990 p. — ISBN-10: 1449373666, ISBN-13: 978-1-449-37371-9.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 th
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.