There may be no better way to learn how to program than by dissecting real, representative examples written in your language of choice. In Ruby by Example, author Kevin Baird analyzes 44 Ruby scripts, offering step-by- step explanations of how the code works and how to modify it to fit your needs. Baird’s examples demonstrate key features of the language (such as inheritance, encapsulation, higher- order functions, and recursion), while simultaneously solving difficult problems (such as validating XML, creating a bilingual program, and creating command- line interfaces). Each chapter builds upon the next, and each key concept is highlighted in the margin to make it easier for you to navigate the book. You’ll learn how to: • Use the interactive Ruby shell (irb) to learn key features of the language • Extend Ruby using RubyGems, the Ruby package manager • Create numerical utilities, as well as utilities that process and analyze HTML/XML • Implement purely functional and metaprogramming techniques to save time and effort www.nostarch.com TH E F I N EST I N G E E K E NTE RTA I N M E NT™ SHELVE IN: PROGRAM M ING/RUBY $34.95 ($43.95 CDN) ® • Optimize, profile, and test your code to make sure that it not only does its job, but does it well • Create complex utilities that model natural selection, discover mysterious patterns in the Bible (and in Moby-Dick) that “predict” the future, and pick songs to play for a radio station • Create web applications using Rails Ruby is the fastest growing programming language today, and for good reason: Its elegant syntax and readable code make for prolific and happy programmers. But it can be difficult to understand and implement without a little help. Ruby by Example shows you how to take advantage of Ruby as you explore Ruby’s fundamental concepts in action. A B O U T T H E A U T H O R Kevin C. Baird received his Ph.D. from the State University of New York at Buffalo. He originally wrote his dissertation in Python but rewrote the project after discovering Ruby, and he hasn’t looked back since. He has presented at RubyConf and written articles for Linux Journal, Music & Computers magazine, and the New Interfaces for Musical Expression conference proceedings. E X P L O R I N G F U N C T I O N A L C O D E “ I LAY F LAT .” Th is book uses RepKover — a durable b ind ing that won’t snap shut. Printed on recycled paper R U B Y B Y E X A M P L E K E V I N C . B A I R D ® C O N C E P T S A N D C O D E R U B Y B Y E X A M P L E R U B Y B Y E X A M P L E B A IR D
(This page has no text content)
(This page has no text content)
RUBY BY EXAMPLE C o n c e p t s a n d C o d e by Kevin C. Baird San Francisco ®
RUBY BY EXAMPLE. Copyright © 2007 by Kevin C. Baird. 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. 11 10 09 08 07 1 2 3 4 5 6 7 8 9 ISBN-10: 1-59327-148-4 ISBN-13: 978-1-59327-148-0 Publisher: William Pollock Production Editor: Elizabeth Campbell Cover and Interior Design: Octopod Studios Developmental Editor: Tyler Ortman Technical Reviewer: Pat Eyler Copyeditor: Megan Dunchak Compositors: Christina Samuell and Riley Hoffman Proofreader: Publication Services, Inc. Indexer: Nancy Guenther For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 555 De Haro Street, Suite 250, San Francisco, CA 94107 phone: 415.863.9900; fax: 415.863.9950; info@nostarch.com; www.nostarch.com Library of Congress Cataloging-in-Publication Data Baird, Kevin C. Ruby by example : concepts and code / Kevin C. Baird. p. cm. Includes index. ISBN-13: 978-1-59327-148-0 ISBN-10: 1-59327-148-4 1. Object-oriented programming (Computer science) 2. Ruby (Computer program language) I. Title. QA76.64.B27 2007 005.1'17--dc22 2007018653 No Starch Press and the No Starch Press logo are registered trademarks 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. Printed on recycled paper in the United States of America
This book is dedicated to my parents, who bought the first computer I ever programmed.
(This page has no text content)
B R I E F C O N T E N T S Acknowledgments ........................................................................................................ xvii Introduction: What Is Ruby?............................................................................................xix Chapter 1: Interactive Ruby and the Ruby Environment ........................................................1 Chapter 2: Amusements and Simple Utilities .....................................................................13 Chapter 3: Programmer Utilities ......................................................................................33 Chapter 4: Text Manipulation .........................................................................................51 Chapter 5: Number Utilities............................................................................................71 Chapter 6: Functionalism with Blocks and Procs ................................................................99 Chapter 7: Using, Optimizing, and Testing Functional Techniques.....................................121 Chapter 8: HTML and XML Tools...................................................................................141 Chapter 9: More Complex Utilities and Tricks, Part I........................................................161 Chapter 10: More Complex Utilities and Tricks, Part II .....................................................185 Chapter 11: CGI and the Web.....................................................................................205 Chapter 12: RubyGems and Rails Preparation ................................................................223 Chapter 13: A Simple Rails Project................................................................................237 Appendix: How Does Ruby Compare to Other Languages?..............................................261 Index .........................................................................................................................267
(This page has no text content)
C O N T E N T S I N D E T A I L ACKNOWLEDGMENTS xvii INTRODUCTION: WHAT IS RUBY? xix Acquiring and Configuring Ruby ............................................................................... xx On a Unix or Unix-like System ..................................................................... xx On a Windows System .............................................................................. xxi Motivations for the Book ......................................................................................... xxi Conventions ............................................................................................ xxii Summary of Chapters ............................................................................... xxii 1 INTERACTIVE RUBY AND THE RUBY ENVIRONMENT 1 Starting irb .............................................................................................................. 2 Using irb ................................................................................................................. 2 Expressions ................................................................................................ 2 Everything Is an Object ................................................................................ 2 Integers, Fixnums, and Bignums .................................................................... 3 Addition, Concatenation, and Exceptions ....................................................... 4 Casting ...................................................................................................... 4 Arrays ....................................................................................................... 5 Booleans .................................................................................................... 6 Flow Control ............................................................................................... 6 Methods ..................................................................................................... 8 Variables ................................................................................................... 9 Constants ................................................................................................. 10 Using the Ruby Interpreter and Environment ............................................................... 10 2 AMUSEMENTS AND SIMPLE UTILITIES 13 #1 Is It Payday? (check_payday.rb) .......................................................................... 14 The Code ................................................................................................. 14 How It Works ........................................................................................... 14 The Results ............................................................................................... 16 #2 Random Signature Generator (random_sig.rb and random_sig-windows.rb) ............. 16 The Code ................................................................................................. 16 How It Works ........................................................................................... 16 Running the Script ..................................................................................... 19 The Results ............................................................................................... 19 Hacking the Script ..................................................................................... 19 #3 The 99 Bottles of Beer Song (99bottles.rb) ............................................................ 20 The Code ................................................................................................. 20 How It Works ........................................................................................... 21
x Conten ts in Detai l Running the Script ..................................................................................... 25 The Results ............................................................................................... 25 #4 Sound File Player (shuffle_play.rb) ....................................................................... 25 The Code ................................................................................................. 26 How It Works ........................................................................................... 27 Running the Script ..................................................................................... 29 The Results ............................................................................................... 29 Hacking the Script ..................................................................................... 30 Chapter Recap ....................................................................................................... 31 3 PROGRAMMER UTILITIES 33 #5 What Is Truth? (boolean_golf.rb) ......................................................................... 33 The Code ................................................................................................. 34 How It Works ........................................................................................... 34 Hacking the Script ..................................................................................... 36 Running the Script ..................................................................................... 36 The Results ............................................................................................... 36 #6 Making a List (array_join.rb) ............................................................................... 36 The Code ................................................................................................. 37 How It Works ........................................................................................... 37 Running the Script ..................................................................................... 39 Hacking the Script ..................................................................................... 39 #7 Command-Line Interface (uses_cli.rb and simple_cli.rb) .......................................... 39 The Code ................................................................................................. 40 How It Works ........................................................................................... 42 Running the Script ..................................................................................... 44 Hacking the Script ..................................................................................... 45 #8 Palindromes (palindrome.rb and palindrome2.rb) ................................................. 45 The Code ................................................................................................. 45 How It Works ........................................................................................... 46 Hacking the Script ..................................................................................... 46 Running the Script ..................................................................................... 47 The Results ............................................................................................... 48 Chapter Recap ....................................................................................................... 49 4 TEXT MANIPULATION 51 #9 End-of-Line Conversion (dos2unix.rb) ................................................................... 51 The Code ................................................................................................. 52 How It Works ........................................................................................... 52 Running the Script ..................................................................................... 55 The Results ............................................................................................... 56 Hacking the Script ..................................................................................... 56 #10 Showing Line Numbers (line_num.rb) ................................................................. 57 The Code ................................................................................................. 57 How It Works ........................................................................................... 57 Running the Script ..................................................................................... 58 The Results ............................................................................................... 58
Conten ts in Detai l xi #11 Wrapping Lines of Text (softwrap.rb) ................................................................. 59 The Code ................................................................................................. 59 Running the Script ..................................................................................... 62 The Results ............................................................................................... 62 Hacking the Script ..................................................................................... 62 #12 Counting Words in a File (word_count.rb) .......................................................... 62 The Code ................................................................................................. 63 How It Works ........................................................................................... 64 Running the Script ..................................................................................... 64 The Results ............................................................................................... 64 #13 Word Histogram (most_common_words.rb) ........................................................ 65 The Code ................................................................................................. 65 How It Works ........................................................................................... 65 Running the Script ..................................................................................... 67 The Results ............................................................................................... 67 Hacking the Script ..................................................................................... 67 #14 Rotating Characters in a String (rotate.rb) .......................................................... 68 The Code ................................................................................................. 68 How It Works ........................................................................................... 68 Running the Script ..................................................................................... 69 The Results ............................................................................................... 69 Chapter Recap ....................................................................................................... 70 5 NUMBER UTILITIES 71 #15 Computing Powers (power_of.rb) ...................................................................... 72 The Code ................................................................................................. 72 How It Works ........................................................................................... 73 Running the Script ..................................................................................... 74 The Results ............................................................................................... 75 #16 Adding Commas to Numbers (commify.rb) ......................................................... 75 Inheritance ............................................................................................... 75 Modules ................................................................................................... 76 The Code ................................................................................................. 76 How It Works ........................................................................................... 78 Running the Script ..................................................................................... 81 The Results ............................................................................................... 81 #17 Roman Numerals (roman_numeral.rb) ................................................................ 81 The Code ................................................................................................. 82 How It Works ........................................................................................... 83 Running the Script ..................................................................................... 86 The Results ............................................................................................... 86 Hacking the Script ..................................................................................... 87 #18 Currency Conversion, Basic (currency_converter1.rb) .......................................... 87 The Code ................................................................................................. 88 How It Works ........................................................................................... 89 Running the Script ..................................................................................... 90 The Results ............................................................................................... 90 Hacking the Script ..................................................................................... 90
xii Content s i n De ta i l #19 Currency Conversion, Advanced (currency_converter2.rb) ................................... 90 The Code ................................................................................................. 91 How It Works ........................................................................................... 93 Running the Script ..................................................................................... 97 The Results ............................................................................................... 97 Hacking the Script ..................................................................................... 98 Chapter Recap ....................................................................................................... 98 6 FUNCTIONALISM WITH BLOCKS AND PROCS 99 #20 Our First lambda (make_incrementer.rb) .......................................................... 100 The Code ............................................................................................... 100 How It Works ......................................................................................... 101 The Results ............................................................................................. 101 #21 Using Procs for Filtering (matching_members.rb) ............................................... 102 The Code .............................................................................................. 102 How It Works ......................................................................................... 102 Running the Script ................................................................................... 103 The Results ............................................................................................. 103 #22 Using Procs for Compounded Filtering (matching_compound_members.rb) ........... 103 The Code ............................................................................................... 104 How It Works ......................................................................................... 105 The Results ............................................................................................. 107 Hacking the Script ................................................................................... 108 #23 Returning Procs as Values (return_proc.rb) ........................................................ 108 The Code ............................................................................................... 108 The Results ............................................................................................. 109 How It Works ......................................................................................... 109 #24 Nesting lambdas ........................................................................................... 111 The Code ............................................................................................... 111 How It Works ......................................................................................... 112 #25 Procs for Text (willow_and_anya.rb) ................................................................ 112 The Code ............................................................................................... 112 How It Works ......................................................................................... 115 Running the Script ................................................................................... 118 The Results ............................................................................................. 118 Hacking the Script ................................................................................... 119 Chapter Recap ..................................................................................................... 119 7 USING, OPTIMIZING, AND TESTING FUNCTIONAL TECHNIQUES 121 #26 Basic Factorials and Fibonaccis (factorial1.rb through fibonacci5.rb) ................... 122 The Code ............................................................................................... 122 How It Works ......................................................................................... 123 The Results ............................................................................................. 123 Hacking the Script ................................................................................... 124
Conten t s in Detai l xiii #27 Benchmarking and Profiling (tests/test_opts.rb) ................................................. 128 Benchmarking ......................................................................................... 128 The Code ............................................................................................... 128 How It Works ......................................................................................... 129 Running the Script ................................................................................... 130 The Results ............................................................................................. 130 Profiling ................................................................................................. 131 Hacking the Script ................................................................................... 132 #28 Converting Temperatures (temperature_converter.rb) ......................................... 132 The Code ............................................................................................... 132 How It Works ......................................................................................... 134 The Results ............................................................................................. 136 Hacking the Script ................................................................................... 136 #29 Testing temperature_converter.rb (tests/test_temp_converter.rb) ........................... 137 The Code ............................................................................................... 137 The Results ............................................................................................. 138 How It Works ......................................................................................... 139 Hacking the Script ................................................................................... 139 Chapter Recap ..................................................................................................... 140 8 HTML AND XML TOOLS 141 #30 Cleaning Up HTML (html_tidy.rb) .................................................................... 141 The Code ............................................................................................... 142 How It Works ......................................................................................... 144 Running the Script ................................................................................... 146 The Results ............................................................................................. 147 Hacking the Script ................................................................................... 148 #31 Counting Tags (xml_tag_counter.rb) ................................................................. 148 The Code ............................................................................................... 149 How It Works ......................................................................................... 150 Running the Script ................................................................................... 153 The Results ............................................................................................. 153 Hacking the Script ................................................................................... 153 #32 Extracting Text from XML (xml_text_extractor.rb) ................................................ 154 The Code ............................................................................................... 154 How It Works ......................................................................................... 155 Running the Script ................................................................................... 155 The Results ............................................................................................. 155 Hacking the Script ................................................................................... 156 #33 Validating XML (xml_well_formedness_checker.rb) ............................................ 156 The Code ............................................................................................... 156 How It Works ......................................................................................... 157 Running the Script ................................................................................... 158 The Results ............................................................................................. 158 Hacking the Script ................................................................................... 158 Chapter Recap ..................................................................................................... 159
xiv Content s i n De ta i l 9 MORE COMPLEX UTILITIES AND TRICKS, PART I 161 #34 Finding Codes in the Bible or Moby-Dick (els_parser.rb) .................................... 161 The Code ............................................................................................... 162 How It Works ......................................................................................... 164 Running the Script ................................................................................... 167 The Results ............................................................................................. 167 Hacking the Script ................................................................................... 168 #35 Mutating Strings into Weasels (methinks.rb) ...................................................... 168 The Code ............................................................................................... 168 How It Works ......................................................................................... 171 Running the Script ................................................................................... 174 The Results ............................................................................................. 174 Hacking the Script ................................................................................... 175 #36 Mutating the Mutation of Strings into Weasels (methinks_meta.rb) ....................... 176 The Code ............................................................................................... 177 How It Works ......................................................................................... 179 Running the Script ................................................................................... 181 The Results ............................................................................................. 181 Hacking the Script ................................................................................... 182 Chapter Recap ..................................................................................................... 183 10 MORE COMPLEX UTILITIES AND TRICKS, PART I I 185 #37 Overnight DJ (radio_player1.rb) ...................................................................... 186 The Code ............................................................................................... 186 How It Works ......................................................................................... 187 The Results ............................................................................................. 189 Hacking the Script ................................................................................... 190 #38 Better Overnight DJ (radio_player2.rb) ............................................................. 190 The Code ............................................................................................... 190 How It Works ......................................................................................... 191 The Results ............................................................................................. 192 Hacking the Script ................................................................................... 193 #39 Numbers by Name (to_lang.rb) ...................................................................... 193 The Code ............................................................................................... 194 How It Works ......................................................................................... 198 The Results ............................................................................................. 201 Hacking the Script ................................................................................... 202 #40 Elegant Maps and Injects (symbol.rb) ............................................................... 203 The Code ............................................................................................... 203 How It Works ......................................................................................... 203 The Results ............................................................................................. 204 Hacking the Script ................................................................................... 204 Chapter Recap ..................................................................................................... 204
Conten ts i n Detai l xv 11 CGI AND THE WEB 205 Common Gateway Interface .................................................................................. 206 Preparation and Installation ................................................................................... 206 #41 A Simple CGI Script (simple_cgi.rb) ................................................................. 207 The Code ............................................................................................... 207 How It Works ......................................................................................... 208 The Results ............................................................................................. 210 Hacking the Script ................................................................................... 210 #42 Mod Ruby (mod_ruby_demo.rhtml and mod_ruby_demo.conf) ............................ 211 The Code ............................................................................................... 211 How It Works ......................................................................................... 213 The Results ............................................................................................. 214 Hacking the Script ................................................................................... 214 #43 CSS Stylesheets, Part I (stylesheet.rcss) ............................................................. 215 The Code ............................................................................................... 215 How It Works ......................................................................................... 216 The Results ............................................................................................. 217 Hacking the Script ................................................................................... 218 #44 CSS Stylesheets, Part II (stylesheet2.rcss) .......................................................... 218 The Code ............................................................................................... 218 How It Works ......................................................................................... 220 The Results ............................................................................................. 220 Hacking the Script ................................................................................... 221 Chapter Recap ..................................................................................................... 221 12 RUBYGEMS AND RAILS PREPARATION 223 RubyGems ........................................................................................................... 223 Installing RubyGems ................................................................................ 224 Using RubyGems ..................................................................................... 224 Rails Preparation .................................................................................................. 227 What Is Rails? ......................................................................................... 228 Other Options for Installing Rails ............................................................... 228 Databases .............................................................................................. 229 The Structure of a Rails Application ........................................................... 229 Chapter Recap ..................................................................................................... 235 13 A SIMPLE RAILS PROJECT 237 Creating the Application ....................................................................................... 237 Initial Creation ........................................................................................ 238 Preparing the Database ........................................................................... 238 Adding Data .......................................................................................... 238 Creating the Model and Controllers ........................................................... 240
xvi Content s i n De ta i l Dissecting the Application ..................................................................................... 241 Dissecting the Photo Model ....................................................................... 241 Dissecting the Controllers ......................................................................... 242 Dissecting the Helpers .............................................................................. 245 Dissecting the Album Controller’s Views ..................................................... 251 Dissecting the Feed Controller’s images View ............................................. 254 Dissecting the Album Controller’s Layout .................................................... 256 Using CSS .............................................................................................. 257 Using the Application ........................................................................................... 257 Learning More About Rails .................................................................................... 260 Chapter Recap ..................................................................................................... 260 APPENDIX HOW DOES RUBY COMPARE TO OTHER LANGUAGES? 261 C ....................................................................................................................... 261 Haskell ............................................................................................................... 262 Java ................................................................................................................... 262 Lisp .................................................................................................................... 263 Perl .................................................................................................................... 264 PHP .................................................................................................................... 264 Python ................................................................................................................ 265 Smalltalk ............................................................................................................. 265 Summary of Ruby vs. Other Languages ................................................................... 266 INDEX 267
A C K N O W L E D G M E N T S The most fervent thanks are due to my wife, Jennifer Cornish, who put up with my focusing too much on this book while she was finishing up her doctoral dissertation. Thanks to Jon Phillips, Michael Ivancic, Aubrey Keus, and Scott Bliss for helpful comments. Jon Phillips in particular gave very useful technical advice in the early stages of writing, and I think of him as the unofficial early tech reviewer. Thanks are obviously also due to the official tech reviewer Pat Eyler, whose influence made this is a much better book than it would otherwise have been. Thanks as well to professors Richard Dawkins of Oxford University and Brendan McKay of the Australian National University for their cooperation in my referencing their work. Finally, thanks to everyone at No Starch Press and to Matz for creating Ruby in the first place.
(This page has no text content)
Comments 0
Loading comments...
Reply to Comment
Edit Comment