VISUAL QUICKSTART GUIDE RUBY Larry Ullman Peachpit Press Visual QuickStart Guide Ruby Larry Ullman Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: www.peachpit.com To report errors, please send a note to: [email protected] Peachpit Press is a division of Pearson Education. Copyright © 2009 by Larry Ullman Editor: Rebecca Gulick Copy Editor: Bob Campbell Production Coordinator: Myrna Vladic Compositor: Debbie Roberti Indexer: Jack Lewis Cover Design: Peachpit Press Technical Reviewer: Fabio Cevasco Notice of rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected]. Notice of liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit Press 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 instructions contained in this book or by the computer software and hardware products described in it. Trademarks Visual QuickStart Guide is a registered trademark of Peachpit Press, a division of Pearson Education. Macintosh and Mac OS X are registered trademarks of Apple Computer, Inc. Microsoft and Windows are registered trademarks of Microsoft Corp. Other product names used in this book may be trademarks of their own respective owners. Images of Web sites in this book are copyrighted by the original holders and are used with their kind permission. This book is not officially endorsed by nor affiliated with any of the above companies. 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 Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. ISBN-13: 978-0-321-55385-0 ISBN-10: 0-321-55385-3 9 8 7 6 5 4 3 2 1 Printed and bound in the United States of America Dedication: I dedicate this book to all those who freely donate their time, money, and efforts to benefit others. To those who apply their expertise to an open-source technology like Ruby, provide help in an online forum, and assist in their local community, and to so many others, I say thanks. Bucketfuls of warm fuzzies to: She without whom I would be so much less of a writer, Rebecca Gulick. Bob Campbell, for keeping things tidy. Debbie Roberti and Myrna Vladic, for turning a grab bag of files into a coherent book. Jack Lewis for creating the index. Everyone else at Peachpit Press and Pearson, for everything they do! Fabio Cevasco, for the thorough technical review. Jessica, Sam, and Zoe, for everything, everything, everything else. Table of Contents Introduction ix Chapter 1: Getting Started 1 Installation on Windows. .2 Installation on Mac OS X. .4 Testing an Installation. .7 Ruby Documentation. 9 Interactive Ruby. 12 Table of Contents Table Customizing irb. 16 Chapter 2: Simple Scripts 19 Creating a Basic Script . 20 Execution on Windows. 22 Command-Line Execution. 24 Making Scripts Executable . 26 Creating Output. 28 Taking Input. 30 Making Comments. 32 Chapter 3: Simple Types 35 Creating Numbers . 36 Performing Arithmetic. 38 Numeric Methods. 40 Creating Strings. 43 Interpolation and Escaping. 45 Common String Methods. 48 Creating Multiline Strings. 50 Using Constants. 53 Dates and Times. 55 Chapter 4: Arrays, Ranges, and Hashes 59 Creating Arrays. 60 Common Array Methods. 63 Adding Elements. 67 Removing Elements. 70 Arrays and Strings. 72 Using Ranges. 74 Creating a Hash. 77 Common Hash Methods . 79 Contents Chapter 5: Control Structures 81 Operators. 82 Basic Conditionals. 85 Extended Conditionals. 89 The Conditional Operator. 92 Case Statements. 96 Basic Loops. 100 Numeric Iterators. 104 Collection Iterators . 107 Chapter 6: Creating Methods 111 Simple Methods . 112 Returning Values . 114 Taking Arguments. 118 Default Argument Values . 121 Using self. 123 Variable-Length Arguments. 125 Methods and Blocks. 129 Chapter 7: Creating Classes 133 Simple Classes. 134 Instance Variables. 138 Using Accessors . 141 Creating Constructors. 144 Table of Contents Table Defining Operators. 148 Other Special Methods. 157 Validation and Duck Typing. 162 Chapter 8: Inheritance and More 167 Basic Inheritance . 168 Overriding Methods. 173 Chaining Methods. 176 Access Control. 180 Class Variables. 186 Class Methods. 189 Chapter 9: Modules and Includes 195 Modules as Namespaces . 196 Modules as Mixins. 200 Requiring Files. 204 Ruby Standard Library . 209 i Contents Chapter 10: Regular Expressions 211 Performing Matches . 212 Defining Simple Patterns. 215 Using Anchors. 218 Using Quantifiers. 221 Using Character Classes. 224 Using Modifiers. 228 Finding Matches. 230 Performing Substitutions. 234 Chapter 11: Debugging and Error Handling 239 Using the Ruby Debugger. 240 Exception Handling. 246 Handling Exceptions by Type. 250 Raising Exceptions. 253 Unit Testing. 258 of Contents Table Chapter 12: RubyGems 265 Installing RubyGems. 266 Managing and Installing Gems. 269 Using Gems. 273 The creditcard Gem. 276 The Highline Gem. 278 The RedCloth Gem. 284 Chapter 13: Directories and Files 287 The Basics. 288 Accessing Directory Contents . 291 Directory and File Properties . 294 Permissions. 297 Creating, Moving, Copying, and Deleting. 301 Reading from Files. 304 Writing to Files. 307 Using FasterCSV. 311 Chapter 14: Databases 315 Getting Started. 316 Executing Simple Queries . 319 Inserting Records. 321 Retrieving Records. 326 Performing Transactions. 330 ii Contents Chapter 15: Networking 335 Creating a Socket Server. 336 Using Threads. 339 Creating a Socket Client. 344 HTTP Connections . 347 Handling RSS Feeds. 351 Chapter 16: Ruby on Rails 355 A Rails Primer. 356 Getting Started. 358 Database Configuration. 361 Creating the Database. 364 Trying the Site. 369 Customizing Models. 371 Customizing Views . 375 Customizing Controllers . 382 Chapter 17: Dynamic Programming 387 OS Integration. 388 Tainted Data . 392 Safe Levels. 396 Procs and Lambdas. 400 407 Index Table of Contents Table iii iIntroduction Introduction If you’re looking at this book and reading this introduction, you probably have these two questions: u Should I learn Ruby? u Is this the book for me? Introduction Of course, the answers to these questions depend upon who you are and what your situation is. But the fact that you’re curious about Ruby and this book would lead me to suggest that the answer to both question is “Yes!” But I admit I have a biased opinion. There are a lot of programming languages out there and lots of books on each language. If you quickly read just the next couple of pages, I’ll outline my case for Ruby and this book in detail, but know that Ruby is a language that’s quite powerful and useful but still remarkably easy to learn. This book, then, has the same aspirations: it’s very easy to learn from, and it focuses on providing the most useful information above all. ix Introduction What Is Ruby? It’s difficult to describe what Rubyis without outright convincing you to use it. Such is the problem when you’re talking about some- thing special. But I’ll try to restrain myself by starting with the more mundane details about Ruby. Ruby is a dynamic object-oriented program- ming language that can be used for just about any purpose: text processing, system utilities, Web development, even graphi- cal applications. Ruby was initially created by Yukihiro Matsumoto, aka “Matz,” and released to the public in 1995. In 2005 and 2006, largely thanks to the popularity of the Ruby on Rails Web development framework (covered in Chapter 16, “Ruby on Rails”), Ruby came to the forefront of the worldwide What Is Ruby? What computing consciousness. Today, Ruby is one of the ten most-used programming languages, and its user base is predicted to quadruple by 2013. Unlike C or C++ code, which is compiled into an executable application, Ruby code is most often run through an interpreter. The inter- preter works on most operating systems, however, and the large majority of Ruby code is cross-platform compatible without modification. Last but not least, Ruby is an open source project: it’s free for anyone to use, modify, or distribute. This also means that Ruby is maintained—and constantly being improved upon—by a broad spectrum of developers around the globe. While I was writing this book, the stable ver- sion of Ruby was 1.8.6 (version 1.8.7, a minor update, was released just as the book went to print). Ruby 1.9 is in development, and many of its features and changes are introduced in this book, although not formally covered. x Introduction Why Use Ruby? tures of the language itself, again, while an application is running. For example, your Without further ado, my top three reasons code can modify the definition of theString for why you should use Ruby: class—i.e., the representation of any quoted characters—on the fly! 1. In all likelihood, it can be used for what- ever tasks you need to address. As for Ruby’s power, that comes, in part, from its Standard Library, which defines over 2. It’s flexible and powerful, yet still 9,000 methods that you can use in your code.