Ruby is famous for being easy to learn, but most users only scratch the surface of what it can do. While other books focus on Ruby’s trendy features, The Book of ™ Ruby reveals the secret inner workings of one of the world’s most popular programming languages, teaching you to write clear, maintainable code. You’ll start with the basics—types, data structures, and control flows—and progress to advanced features like blocks, mixins, metaclasses, and beyond. Rather than bog you down with a lot of theory, The Book of Ruby takes a hands-on approach and focuses on making you productive from day one. As you follow along, you’ll learn to: • Leverage Ruby’s succinct and flexible syntax to maximize your productivity • Balance Ruby’s functional, imperative, and object- oriented features • Write self-modifying programs using dynamic programming techniques • Create new fibers and threads for lightweight multitasking M A S T E R R U B Y F R O M T H E I N S I D E O U T • Catch and recover from execution errors with robust exception handling • Develop powerful web applications with the Ruby on Rails framework Each chapter includes a “Digging Deeper” section that shows you how Ruby works under the hood, so you won’t be caught off guard by its deceptively simple scoping, multithreading features, or precedence rules. Whether you’re new to programming or just new to Ruby, The Book of Ruby is your guide to mastering rapid, real-world software development with this unique and elegant language. A B O U T T H E A U T H O R Huw Collingbourne is the Director of Technology for SapphireSteel Software, developer of the Ruby In Steel IDE. With 30 years of programming experience, he has written programming columns for numerous magazines, presented features on computing for BBC Television, and currently edits the online technical journal Bitwise Magazine. He has previously released two free ebooks on Ruby—The Little Book of Ruby and The Book of Ruby. Covers Ruby 1.8 and 1.9 SHELVE IN : COM PUTERS/PROGRAM M ING LANGUAGES/RUBY $39.95 ($45.95 CDN) www.nostarch.com TH E F I N EST I N G E E K E NTE RTA I N M E NT™ “ I L I E F LAT .” Th is book uses a lay-flat b ind ing that won’t snap shut. FSC LOGO H U W C O L L I N G B O U R N E T H E B O O K O F R U B Y A H A N D S - O N G U I D E F O R T H E A D V E N T U R O U S ™ ™ T H E B O O K O F R U B Y T H E B O O K O F R U B Y C O L L IN G B O U R N E
(This page has no text content)
(This page has no text content)
THE BOOK OF™ RUBY A H a n d s - O n G u i d e f o r t h e A d v e n t u r o u s by Huw Col l ingbourne San Francisco
THE BOOK OF RUBY. Copyright © 2011 by Huw Collingbourne All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. Printed in Canada 15 14 13 12 11 1 2 3 4 5 6 7 8 9 ISBN-10: 1-59327-294-4 ISBN-13: 978-1-59327-294-4 Publisher: William Pollock Production Editor: Serena Yang Developmental Editor: Keith Fancher Technical Reviewer: Pat Eyler Copyeditor: Kim Wimpsett Compositors: Serena Yang and Alison Law Proofreader: Ward Webber For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 38 Ringold Street, San Francisco, CA 94103 phone: 415.863.9900; fax: 415.863.9950; info@nostarch.com; www.nostarch.com Library of Congress Cataloging-in-Publication Data Collingbourne, Huw. The book of Ruby : a hands-on guide for the adventurous / Huw Collingbourne. p. cm. Includes index. ISBN-13: 978-1-59327-294-4 ISBN-10: 1-59327-294-4 1. Ruby (Computer program language) 2. Object-oriented programming (Computer science) I. Title. QA76.73.R83C65 2011 005.1'17--dc23 2011014782 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. “The Book of” is a trademark of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
B R I E F C O N T E N T S Acknowledgments ..........................................................................................................xv Introduction .................................................................................................................xvii Chapter 1: Strings, Numbers, Classes, and Objects ............................................................1 Chapter 2: Class Hierarchies, Attributes, and Class Variables ............................................15 Chapter 3: Strings and Ranges .......................................................................................33 Chapter 4: Arrays and Hashes .......................................................................................47 Chapter 5: Loops and Iterators........................................................................................67 Chapter 6: Conditional Statements ..................................................................................83 Chapter 7: Methods ......................................................................................................97 Chapter 8: Passing Arguments and Returning Values .......................................................121 Chapter 9: Exception Handling.....................................................................................139 Chapter 10: Blocks, Procs, and Lambdas .......................................................................155 Chapter 11: Symbols...................................................................................................181 Chapter 12: Modules and Mixins..................................................................................191 Chapter 13: Files and IO .............................................................................................213 Chapter 14: YAML ......................................................................................................227 Chapter 15: Marshal...................................................................................................239
vi Brie f Conten ts Chapter 16: Regular Expressions ..................................................................................249 Chapter 17: Threads ...................................................................................................263 Chapter 18: Debugging and Testing .............................................................................283 Chapter 19: Ruby on Rails ...........................................................................................299 Chapter 20: Dynamic Programming ..............................................................................325 Appendix A: Documenting Ruby with RDoc ....................................................................345 Appendix B: Installing MySQL for Ruby on Rails..............................................................349 Appendix C: Further Reading .......................................................................................353 Appendix D: Ruby and Rails Development Software ........................................................357 Index .........................................................................................................................361
C O N T E N T S I N D E T A I L ACKNOWLEDGMENTS xv INTRODUCTION xvii What Is Ruby? ......................................................................................................xviii What Is Rails? .......................................................................................................xviii Matters of Ruby Style .............................................................................................xviii How to Read This Book ........................................................................................... xix Digging Deeper ..................................................................................................... xix Making Sense of the Text ........................................................................................ xix Downloading Ruby .................................................................................................. xx Getting the Source Code of the Sample Programs ...................................................... xxi Running Ruby Programs .......................................................................................... xxi The Ruby Library Documentation .............................................................................. xxi 1 STRINGS, NUMBERS, CLASSES, AND OBJECTS 1 Getting and Putting Input ........................................................................................... 2 Strings and Embedded Evaluation .............................................................................. 2 Numbers ................................................................................................................. 3 Comments ............................................................................................................... 4 Testing a Condition: if..then ....................................................................................... 4 Local and Global Variables ........................................................................................ 5 Classes and Objects ................................................................................................. 6 Instance Variables ....................................................................................... 7 Retrieving Data from an Object ..................................................................... 7 Messages, Methods, and Polymorphism ......................................................... 9 Constructors: new and initialize .................................................................. 10 Inspecting Objects ..................................................................................... 11 2 CLASS HIERARCHIES, ATTRIBUTES, AND CLASS VARIABLES 15 Superclasses and Subclasses ................................................................................... 17 Passing Arguments to the Superclass ......................................................................... 18 Accessor Methods .................................................................................................. 19 Attribute Readers and Writers .................................................................................. 20 Calling Methods of a Superclass .............................................................................. 23 Class Variables ...................................................................................................... 23 Digging Deeper ...................................................................................................... 25 Superclasses ............................................................................................. 25 The Root of All Classes ............................................................................... 29 Constants Inside Classes ............................................................................ 30 Partial Classes .......................................................................................... 30
viii Contents in Detai l 3 STRINGS AND RANGES 33 User-Defined String Delimiters .................................................................................. 35 Backquotes ............................................................................................................ 36 String Handling ...................................................................................................... 36 Concatenation .......................................................................................... 37 What About Commas? .............................................................................. 38 String Assignment ...................................................................................... 38 Indexing into a String ................................................................................ 39 Removing Newline Characters: chop and chomp .......................................... 42 Format Strings ........................................................................................... 43 Ranges ................................................................................................................. 43 Ranges of Strings ...................................................................................... 44 Iterating with a Range ................................................................................ 44 Digging Deeper ...................................................................................................... 45 Heredocs ................................................................................................. 45 String Literals ............................................................................................ 46 4 ARRAYS AND HASHES 47 Arrays .................................................................................................................. 47 Creating Arrays ........................................................................................ 48 Multidimensional Arrays ............................................................................. 50 Iterating over Arrays .................................................................................. 51 Indexing into Arrays .................................................................................. 52 Copying Arrays ........................................................................................ 53 Testing Arrays for Equality .......................................................................... 53 Sorting Arrays .......................................................................................... 54 Comparing Values .................................................................................... 55 Array Methods .......................................................................................... 57 Hashes ................................................................................................................. 58 Creating Hashes ....................................................................................... 58 Indexing into a Hash ................................................................................. 60 Copying a Hash ....................................................................................... 60 Hash Order .............................................................................................. 60 Sorting a Hash .......................................................................................... 61 Hash Methods .......................................................................................... 62 Digging Deeper ...................................................................................................... 63 Treating Hashes as Arrays .......................................................................... 63 Appending vs. Concatenating ..................................................................... 63 Vectors and Matrices ................................................................................. 64 Sets ......................................................................................................... 65 5 LOOPS AND ITERATORS 67 for Loops ............................................................................................................... 67 Blocks and Block Parameters ................................................................................... 70 Iterating upto and downto ....................................................................................... 70
Contents in Detai l ix Multiple Iterator Arguments ...................................................................................... 71 while Loops ........................................................................................................... 72 while Modifiers ......................................................................................... 72 Ensuring a while Loop Executes at Least Once .............................................. 73 until Loops ............................................................................................................. 74 loop ..................................................................................................................... 75 Digging Deeper ...................................................................................................... 76 The Enumerable Module ............................................................................ 76 Custom Comparisons ................................................................................. 77 each and yield .......................................................................................... 81 6 CONDITIONAL STATEMENTS 83 if..then..else ........................................................................................................... 84 and, or, and not .................................................................................................... 85 Negation .............................................................................................................. 86 if..elsif .................................................................................................................. 86 unless ................................................................................................................... 88 if and unless Modifiers ............................................................................................ 88 Case Statements ..................................................................................................... 89 The === Method ....................................................................................... 92 Alternative Case Syntax ............................................................................. 92 Digging Deeper ...................................................................................................... 93 Boolean Operators .................................................................................... 93 Eccentricities of Boolean Operators ............................................................. 94 catch and throw ........................................................................................ 94 7 METHODS 97 Class Methods ....................................................................................................... 97 What Are Class Methods For? ................................................................................. 98 Class Variables ...................................................................................................... 99 Ruby Constructors: new or initialize? ...................................................................... 104 Singleton Methods ................................................................................................ 105 Singleton Classes ................................................................................................. 108 Overriding Methods ............................................................................................. 110 Public, Protected, and Private Methods ................................................................... 111 Digging Deeper .................................................................................................... 114 Protected and Private Methods in Descendant Classes ................................. 114 Invading the Privacy of Private Methods ..................................................... 116 Singleton Class Methods .......................................................................... 116 Nested Methods ...................................................................................... 118 Method Names ....................................................................................... 119 8 PASSING ARGUMENTS AND RETURNING VALUES 121 Summarizing Instance, Class, and Singleton, Methods .............................................. 121 Returning Values .................................................................................................. 123
x Contents in Detai l Returning Multiple Values ...................................................................................... 124 Default and Multiple Arguments ............................................................................. 124 Assignment and Parameter Passing ........................................................................ 125 Integers Are Special ............................................................................................. 127 The One-Way-In, One-Way-Out Principle ................................................................ 128 Modifying Receivers and Yielding New Objects ...................................................... 130 Potential Side Effects of Reliance on Argument Values ............................................... 131 Parallel Assignment .............................................................................................. 133 Digging Deeper .................................................................................................... 134 By Reference or By Value? ....................................................................... 134 Are Assignments Copies or References? ..................................................... 135 Tests for Equality: == or equal? ................................................................. 136 When Are Two Objects Identical? ............................................................. 136 Parentheses Avoid Ambiguity .................................................................... 137 9 EXCEPTION HANDLING 139 rescue: Execute Code When Error Occurs ............................................................... 140 ensure: Execute Code Whether or Not an Error Occurs ............................................ 144 else: Execute Code When No Error Occurs ............................................................. 145 Error Numbers ..................................................................................................... 146 retry: Attempt to Execute Code Again After an Error ................................................. 148 raise: Reactivate a Handled Error ........................................................................... 149 Digging Deeper .................................................................................................... 152 Omitting begin and end ........................................................................... 152 catch..throw ........................................................................................... 152 10 BLOCKS, PROCS, AND LAMBDAS 155 What Is a Block? .................................................................................................. 156 Line Breaks Are Significant .................................................................................... 156 Nameless Functions .............................................................................................. 157 Look Familiar? ..................................................................................................... 158 Blocks and Arrays ................................................................................................ 159 Procs and Lambdas .............................................................................................. 161 Block or Hash? .................................................................................................... 161 Creating Objects from Blocks ................................................................................. 162 What Is a Closure? ............................................................................................... 163 yield ................................................................................................................... 164 Blocks Within Blocks ............................................................................................. 165 Passing Named Proc Arguments ............................................................................ 165 Precedence Rules ................................................................................................. 170 Blocks as Iterators ................................................................................................. 172 Digging Deeper .................................................................................................... 175 Returning Blocks from Methods ................................................................. 175 Blocks and Instance Variables ................................................................... 176 Blocks and Local Variables ....................................................................... 177
Contents in Detai l xi 11 SYMBOLS 181 Symbols and Strings ............................................................................................. 182 Symbols and Variables ......................................................................................... 186 Why Use Symbols? .............................................................................................. 188 Digging Deeper .................................................................................................... 190 What Is a Symbol? .................................................................................. 190 12 MODULES AND MIXINS 191 A Module Is Like a Class . . . ................................................................................. 192 Module Methods .................................................................................................. 192 Modules as Namespaces ...................................................................................... 193 Included Modules, or “Mixins” ............................................................................... 194 Name Conflicts .................................................................................................... 198 Alias Methods ...................................................................................................... 199 Mix In with Care! ................................................................................................. 200 Including Modules from Files ................................................................................. 201 Digging Deeper .................................................................................................... 205 Modules and Classes ............................................................................... 205 Predefined Modules ................................................................................. 205 Scope Resolution ..................................................................................... 208 Module Functions .................................................................................... 209 Extending Objects ................................................................................... 210 Freezing Objects ..................................................................................... 211 13 FILES AND IO 213 Opening and Closing Files .................................................................................... 214 Characters and Compatibility ................................................................................ 216 Files and Directories ............................................................................................. 217 Copying Files ...................................................................................................... 217 Directory Inquiries ................................................................................................ 219 A Discursion into Recursion ................................................................................... 219 Sorting by Size .................................................................................................... 222 Digging Deeper .................................................................................................... 224 Recursion Made Simple ........................................................................... 224 14 YAML 227 Converting to YAML ............................................................................................. 228 Nested Sequences ................................................................................................ 231 Saving YAML Data ............................................................................................... 231 Omitting Variables on Saving ................................................................................ 232 Multiple Documents, One File ................................................................................ 233 A YAML Database ................................................................................................ 234
xii Contents in Detai l Adventures in YAML ............................................................................................. 236 Digging Deeper .................................................................................................... 237 A Brief Guide to YAML ............................................................................ 237 15 MARSHAL 239 Saving and Loading Data ...................................................................................... 239 Omitting Variables on Saving ................................................................................ 240 Saving Singletons ................................................................................................. 242 YAML and Singletons ............................................................................... 242 Marshal and Singletons ........................................................................... 243 Digging Deeper .................................................................................................... 246 Marshal Version Numbers ........................................................................ 246 16 REGULAR EXPRESSIONS 249 Making Matches .................................................................................................. 250 Match Groups ..................................................................................................... 253 MatchData .......................................................................................................... 254 Prematch and Postmatch ....................................................................................... 255 Greedy Matching ................................................................................................. 256 String Methods .................................................................................................... 256 File Operations .................................................................................................... 258 Digging Deeper .................................................................................................... 260 Regular Expression Elements ..................................................................... 260 Regular Expression Examples .................................................................... 260 Symbols and Regular Expressions .............................................................. 261 17 THREADS 263 Creating Threads ................................................................................................. 264 Running Threads .................................................................................................. 264 Going Native ...................................................................................................... 265 The Main Thread .................................................................................................. 266 Thread Status ....................................................................................................... 266 Ensuring That a Thread Executes ............................................................................ 268 Thread Priorities ................................................................................................... 269 The Main Thread Priority ....................................................................................... 271 Mutexes .............................................................................................................. 272 Fibers ................................................................................................................. 275 Digging Deeper .................................................................................................... 278 Passing Execution to Other Threads ........................................................... 278 18 DEBUGGING AND TESTING 283 IRB: Interactive Ruby ............................................................................................. 283 Debugging .......................................................................................................... 286
Contents in Detai l xiii Unit Testing ......................................................................................................... 292 Digging Deeper .................................................................................................... 295 Assertions Available When Unit Testing ..................................................... 295 Line Breaks Are Significant ....................................................................... 296 Graphical Debuggers .............................................................................. 297 19 RUBY ON RAILS 299 Installing Rails ...................................................................................................... 300 Do It Yourself . . . .................................................................................... 300 Or Use an “All-in-One” Installer ................................................................ 301 Model-View-Controller .......................................................................................... 301 A First Ruby on Rails Application ............................................................................ 302 Create a Rails Application ..................................................................................... 302 Create a Controller ............................................................................................... 305 Anatomy of a Simple Rails Application ................................................................... 307 The Generate Controller Script Summarized ............................................................ 309 Create a View ..................................................................................................... 310 Rails Tags ............................................................................................................ 313 Let’s Make a Blog! ............................................................................................... 316 Create the Database ................................................................................ 316 Creating a MySQL Database .................................................................... 317 Scaffolding ............................................................................................. 317 Migration ............................................................................................... 318 Partials .................................................................................................. 318 Test It! .................................................................................................... 320 Digging Deeper .................................................................................................... 322 MVC ..................................................................................................... 322 The Rails Folders ..................................................................................... 323 Other Ruby Frameworks ........................................................................... 324 20 DYNAMIC PROGRAMMING 325 Self-Modifying Programs ....................................................................................... 326 eval .................................................................................................................... 327 Special Types of eval ............................................................................................ 329 Adding Variables and Methods ............................................................................. 331 Creating Classes at Runtime .................................................................................. 333 Bindings .............................................................................................................. 334 send ................................................................................................................... 336 Removing Methods ............................................................................................... 337 Handling Missing Methods .................................................................................... 338 Writing Programs at Runtime ................................................................................. 340 Exploring Further .................................................................................................. 341 Digging Deeper .................................................................................................... 342 Freezing Objects ..................................................................................... 342 A DOCUMENTING RUBY WITH RDOC 345
xiv Contents in Detai l B INSTALLING MYSQL FOR RUBY ON RAILS 349 Downloading MySQL ........................................................................................... 350 Installing MySQL .................................................................................................. 350 Configuring MySQL .............................................................................................. 351 Can’t Find the Database? ...................................................................................... 351 C FURTHER READING 353 Books ................................................................................................................. 353 Ebooks ................................................................................................................ 355 Websites ............................................................................................................. 355 D RUBY AND RAILS DEVELOPMENT SOFTWARE 357 IDEs and Editors ................................................................................................... 357 Web Servers ....................................................................................................... 358 Databases ........................................................................................................... 358 Ruby Implementations ........................................................................................... 359 INDEX 361
A C K N O W L E D G M E N T S I’d like to express my appreciation of all the hard work that’s gone into the preparation of this book by the people at No Starch Press, especially Keith Fancher, Serena Yang, and Bill Pollock. Thanks also to the copy- editor, Kim Wimpsett, and to the technical reviewer, Pat Eyler. For keeping me on the right side of sanity, I owe a debt of gratitude to my two dogs, Beryl and Seven, and to their beautiful mother, Bethan, who, to my enor- mous sadness, died while I was writing this book.
(This page has no text content)
I N T R O D U C T I O N As you are now reading a book on Ruby, I think it is safe to assume you don’t need me to persuade you of the merits of the Ruby language. Instead, I’ll take the somewhat unconven- tional step of starting with a warning: Many people are attracted to Ruby by its simple syntax and its ease of use. They are wrong. Ruby’s syntax may look simple at first sight, but the more you get to know the language, the more you will real- ize that it is, on the contrary, extremely complex. The plain fact of the matter is that Ruby has a number of pitfalls just waiting for unwary programmers to drop into. In this book, it is my aim to guide you safely over the pitfalls and lead you through the choppy waters of Ruby’s syntax and class libraries. In the pro- cess, I’ll be exploring both the smooth, well-paved highways and the gnarlier, bumpy little byways of Ruby. By the end of the journey, you should be able to use Ruby safely and effectively without getting caught by unexpected hazards along the way.
xviii In t roduct ion The Book of Ruby describes versions 1.8.x and 1.9.x of the Ruby language. In most respects, Ruby 1.8 and 1.9 are very similar, and most programs writ- ten for one version will run unmodified in the other. There are important exceptions to this rule, however, and these are noted in the text. Ruby 1.9 may be regarded as a stepping stone toward Ruby 2.0. At the time of writing, a release date for Ruby 2.0 has not been announced. Even so, on the basis of currently available information, I anticipate that most (or all) of the informa- tion on Ruby 1.9 in this book should also apply to Ruby 2.0. What Is Ruby? Ruby is a cross-platform interpreted language that has many features in com- mon with other “scripting” languages such as Perl and Python. It has an eas- ily readable type of syntax that looks somewhat Pascal-like at first sight. It is thoroughly object-oriented and has a good deal in common with the great- granddaddy of “pure” object-oriented languages, Smalltalk. It has been said that the languages that most influenced the development of Ruby were Perl, Smalltalk, Eiffel, Ada, and Lisp. The Ruby language was created by Yukihiro Matsumoto (commonly known as Matz), and it was first released in 1995. What Is Rails? Over the past few years, much of the excitement surrounding Ruby can be attributed to a web development framework called Rails—popularly known as Ruby on Rails. Rails is an impressive framework, but it is not the be-all, end- all of Ruby. Indeed, if you were to leap right into Rails development without first mastering Ruby, you might find that you end up creating applications that you don’t even understand. (This is all too common among Ruby on Rails novices.) Understanding Ruby is a necessary prerequisite for under- standing Rails. You’ll look at Rails in Chapter 19. Matters of Ruby Style Some Ruby programmers have very fixed—or even obsessive—views on what constitutes a “Ruby style” of programming. Some, for example, are passionately wedded to the idea that method_names_use_underscores while variableNamesDoNot. The style of naming in which separate words are indicated by capital letters likeThis is called camel case—and that is the last time it will be mentioned in this book. I have never understood why people get so worked up about naming conventions. You like underscores, I can’t stand them; you say po_ta_toes, I say poTaToes. As far as I am concerned, the way in which you choose to write the names of identifiers in Ruby is of no interest to anyone but you or your programming colleagues. That is not to say that I have no opinions on programming style. On the contrary, I have very strong opinions. In my view, good programming style has nothing to do with naming conventions and everything to do with good
Comments 0
Loading comments...
Reply to Comment
Edit Comment