Prepared Exclusively For Dr. Eugene Wallingford

Transcription

Prepared exclusively for Dr. Eugene Wallingford

Developers the world over talk aboutProgramming Ruby and the Ruby language. . .“Ruby is a wonderfully powerful and useful language, and whenever I’m workingwith it, this book is at my side.”Martin Fowler, Chief Scientist, ThoughtWorks“If your world revolves around Java, as mine did, then you need this outstanding bookto learn all the wonderful things you’re missing. There’s just one catch: you’ll bespoiled from then on. Indeed, after reading just a few pages of Programming Ruby,programming in any language other than Ruby will feel like you’re pushing rope.”Mike Clark, Author and Consultant“Ruby is smart, elegant, and fun, and it deserves a book that’s smart, elegant, and fun.The first edition of Programming Ruby was such a book; the second edition is evenbetter.”James Britt, Administrator, http://ruby-doc.org“The best reason to learn a new programming language is to learn to think differently.The best way to learn to think the Ruby way is to read Programming Ruby. Severalyears ago, with the first edition of this book, I did just that. Since then, I’ve had aconstant stream of enjoyable Ruby programming experiences. This is due in noinsignificant part to the quality of the source from which I learned the language. I’mnot the only person I’ve heard say that every language should have a book like this.”Chad Fowler, Codirector, Ruby Central, Inc.“The PickAxe got me started on Ruby. It is still the first book I turn to.”Ryan Davis, Founder, Seattle.rb“This book changed my life. Sounds rather clichéd, but it’s the truth. After six yearsand 300,000 lines of Java code, I needed a change. That change occurred upon readingthe first edition of this book. With the support of a solid community and ever-growingfoundation of superb libraries, I founded a company that largely profits from applyingRuby to solve real-world problems. Ruby is ready for prime time, and this newversion of the PickAxe will show a waiting world what a gem Ruby really is.”Rich Kilmer, President and CEO, InfoEther LLC“The first edition of PickAxe has been a desk-side companion for years. The secondedition will be an eagerly awaited replacement.”Tom Enebo, JRuby DeveloperPrepared exclusively for Dr. Eugene Wallingford

“The first edition of Programming Ruby brought about no less than the introduction ofRuby on a large scale outside of Japan, in the process becoming the de facto standardpublished language reference and an oft-cited model of clear, effective technicalwriting. The appearance of the second, expanded edition is exciting for Rubyprogrammers around the world and will no doubt attract a fresh wave of newcomers tothis elegant, versatile language.”David A. Black, Ph.D., Codirector, Ruby Central, Inc.“Ruby is my definite choice for all scripting and prototyping issues, and this book willhelp you to discover its usefulness as well as its beauty. Apart from that, it’s really funto read!”Robert Klemme“I bought the first edition of this book the day it was released and had a fantastic timeusing it to learn Ruby. I eventually bought a second copy to keep at home. But Rubyhas changed since then. I’m delighted that this second edition of Programming Rubyis available to help a new round of programmers learn about this fantastic, beautifullanguage. And it’s not just good news for Ruby newbies, of course—like me, mostRuby developers will want a copy (no, make that two) so that all of the details abouttoday’s Ruby will be close at hand.”Glenn Vanderburg, Software Architect, Countrywide Financial“Ruby is one of those great languages that takes an afternoon to start using and years(maybe a lifetime) to master. In C, I’m always having to work around the limitationsof the language; in Ruby, I’m always discovering a neater, cleaner, more efficient wayto do things. Programming Ruby is the essential reference to the Ruby language. Morethan just teaching you the syntax, it teaches you the spirit and the feel of the language.”Ben Giddings“Confucius said, “What you hear, you forget.” He also said, “What you do youunderstand.” But it’s not easy to actually “do” things unless you’re using a greatlanguage with strength in quick and clean prototyping. In my case, this language isRuby! Thank you!”Michael NeumannPrepared exclusively for Dr. Eugene Wallingford

Programming RubyThe Pragmatic Programmers’ GuideSecond EditionDave Thomaswith Chad Fowlerand Andy HuntThe Pragmatic BookshelfRaleigh, North CarolinaPrepared exclusively for Dr. Eugene WallingfordDallas, Texas

Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC, was awareof a trademark claim, the designations have been printed in initial capital letters or in all capitals.Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibilityfor errors or omissions or for damages that may result from the use of information (including programlistings) contained herein.This book is a heavily revised version of the book Programming Ruby, originally published by AddisonWesley. This book is printed with their permission.Our Pragmatic courses, workshops, and other products can help you and your team create better softwareand have more fun. For more information, as well as the latest Pragmatic titles, please visit us athttp://www.pragmaticprogrammer.comCopyright 2005 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may bereproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical,photocopying, recording, or otherwise, without the prior consent of the publisher.Printed in the United States of America.ISBN 0-9745140-5-5Text printed on acid-free paper.Tenth Printing, October 2006Version: 2006-9-20Prepared exclusively for Dr. Eugene Wallingford

ContentsF OREWORDF OREWORDP REFACEROAD M APTO THETO THEF IRST E DITIONS ECOND E DITIONxviixixxxxxviPART I—FACETS OF R UBY1G ETTING S TARTEDInstalling Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Running Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Ruby Documentation: RDoc and ri . . . . . . . . . . . . . . . . . . . . .2RUBY. NEWRuby Is an Object-Oriented LanguageSome Basic Ruby . . . . . . . . . . .Arrays and Hashes . . . . . . . . . . .Control Structures . . . . . . . . . . .Regular Expressions . . . . . . . . . .Blocks and Iterators . . . . . . . . . .Reading and ’Riting . . . . . . . . . .Onward and Upward . . . . . . . . . .32247.9911141617192122C LASSES , O BJECTS , AND VARIABLESInheritance and Messages . . . . . . . . . . . . .Objects and Attributes . . . . . . . . . . . . . . .Class Variables and Class Methods . . . . . . . .Access Control . . . . . . . . . . . . . . . . . . .Variables . . . . . . . . . . . . . . . . . . . . . .232527313537Prepared exclusively for Dr. Eugene Wallingfordv.

CONTENTS4C ONTAINERS , B LOCKS ,viI TERATORS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40404654.55555762646M ORE ABOUT M ETHODSDefining a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Calling a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7474767E XPRESSIONSOperator Expressions . . . . . . .Miscellaneous Expressions . . . .Assignment . . . . . . . . . . . .Conditional Execution . . . . . . .Case Expressions . . . . . . . . .Loops . . . . . . . . . . . . . . . .Variable Scope, Loops, and Blocks589ANDContainers . . . . . . . . . . . . . .Blocks and Iterators . . . . . . . . .Containers Everywhere . . . . . . .S TANDARD T YPESNumbers . . . . . . . .Strings . . . . . . . . .Ranges . . . . . . . . .Regular Expressions . .E XCEPTIONS , C ATCH , ANDThe Exception Class . . . . . . . .Handling Exceptions . . . . . . . .Raising Exceptions . . . . . . . . .Catch and Throw . . . . . . . . . .8182838487929499T HROW.101101102106108M ODULESNamespaces . . . . . . . . . . . . .Mixins . . . . . . . . . . . . . . . .Iterators and the Enumerable ModuleComposing Modules . . . . . . . . .Including Other Files . . . . . . . .110110111113113116.11911912012112510 BASIC I NPUTAND O UTPUTWhat Is an IO Object? . . . . . . .Opening and Closing Files . . . . .Reading and Writing Files . . . . .Talking to Networks . . . . . . . .Prepared exclusively for Dr. Eugene Wallingford

CONTENTSAND P ROCESSESMultithreading . . . . . . . . . . .Controlling the Thread Scheduler .Mutual Exclusion . . . . . . . . .Running Multiple Processes . . . .vii11 T HREADS.127127132133139Test::Unit Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . .Structuring Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Organizing and Running Tests . . . . . . . . . . . . . . . . . . . . . . . .143144148151.12 U NIT T ESTING13 W HEN T ROUBLE S TRIKESRuby Debugger . . .Interactive Ruby . . .Editor Support . . . .But It Doesn’t Work! .But It’s Too Slow! . .155155156157159162PART II—R UBY IN I TS S ETTINGAND I TS W ORLDCommand-Line Arguments . .Program Termination . . . . .Environment Variables . . . . .Where Ruby Finds Its ModulesBuild Environment . . . . . . .14 9519920015 I NTERACTIVE RUBY S HELLCommand Line .Configuration .Commands . . .Restrictions . .rtags and xmp .16 D OCUMENTING RUBYAdding RDoc to Ruby Code .Adding RDoc to C ExtensionsRunning RDoc . . . . . . . .Displaying Program Usage .Prepared exclusively for Dr. Eugene Wallingford.

CONTENTS17 PACKAGE M ANAGEMENTWITHInstalling RubyGems . . . . . . . . . .Installing Application Gems . . . . . . .Installing and Using Gem Libraries . . .Creating Your Own Gems . . . . . . . .AND THE W EBWriting CGI Scripts . . . .Cookies . . . . . . . . . .Improving Performance . .Choice of Web Servers . . .SOAP and Web Services . .More Information . . . . .viiiRUBY G EMS.20320420420621118 RUBY.222222231234234236240Simple Tk Application . . . . . . . . . .Widgets . . . . . . . . . . . . . . . . .Binding Events . . . . . . . . . . . . . .Canvas . . . . . . . . . . . . . . . . . .Scrolling . . . . . . . . . . . . . . . . .Translating from Perl/Tk Documentation.241241242246247249251AND M ICROSOFT W INDOWSGetting Ruby for Windows . . . . . . . . . .Running Ruby Under Windows . . . . . . . .Win32API . . . . . . . . . . . . . . . . . . .Windows Automation . . . . . . . . . . . . .253253254254255.261261264270279280282287290291.19 RUBY T K20 RUBY21 E XTENDING RUBYYour First Extension . . . . . . . .Ruby Objects in C . . . . . . . . .The Jukebox Extension . . . . . .Memory Allocation . . . . . . . .Ruby Type System . . . . . . . . .Creating an Extension . . . . . . .Embedding a Ruby Interpreter . . .Bridging Ruby to Other LanguagesRuby C Language API . . . . . . .Prepared exclusively for Dr. Eugene Wallingford.

CONTENTSixPART III—R UBY C RYSTALLIZED22 T HE RUBY L 347.349350354355361AND O BJECTSHow Classes and Objects Interact .Class and Module Definitions . . .Top-Level Execution EnvironmentInheritance and Visibility . . . . .Freezing Objects . . . . . . . . . .362362370376376377IN THE S AFESafe Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tainted Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .379380381Source Layout . . . . . . . . . . .The Basic Types . . . . . . . . . .Names . . . . . . . . . . . . . . .Variables and Constants . . . . . .Expressions . . . . . . . . . . . .Method Definition . . . . . . . . .Invoking a Method . . . . . . . . .Aliasing . . . . . . . . . . . . . .Class Definition . . . . . . . . . .Module Definitions . . . . . . . .Access Control . . . . . . . . . . .Blocks, Closures, and Proc ObjectsExceptions . . . . . . . . . . . . .Catch and Throw . . . . . . . . . .23 D UCK T YPINGClasses Aren’t Types . . . . . . .Coding like a Duck . . . . . . .Standard Protocols and CoercionsWalk the Walk, Talk the Talk . .24 C LASSES25 L OCKING RUBY26 R EFLECTION , O BJECT S PACE ,Looking at Objects . . . . . . . . .Looking at Classes . . . . . . . . .Calling Methods Dynamically . . .System Hooks . . . . . . . . . . .Tracing Your Program’s ExecutionMarshaling and Distributed Ruby .Compile Time? Runtime? Anytime!.Prepared exclusively for Dr. Eugene Wallingford.AND D ISTRIBUTED RUBY. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .384385386388391393395400

CONTENTSxPART IV—R UBY L IBRARY R EFERENCE27 BUILT- IN C LASSESAlphabetical ListingArray . . . . .Bignum . . . .Binding . . . .Class . . . . .Comparable . .ContinuationDir . . . . . .Enumerable . .Errno . . . . .Exception . .FalseClass . .File . . . . . .File::Stat . .FileTest . . .Fixnum . . . .Float . . . . .GC . . . . . . .Hash . . . . . .Integer . . . .IO . . . . . . .Kernel . . . .Marshal . . . .MatchData . .Math . . . . . .Method . . . .Module . . . .NilClass . . .Numeric . . . .Object . . . .ObjectSpace .Proc . . . . . .Process . . . .Process::GIDProcess::StatusProcess::Sys . .Process::UID . .Range . . . . . . .Regexp . . . . . .AND M ODULES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Prepared exclusively for Dr. Eugene 41546557559562568570573575576579

CONTENTSSignal . . . .String . . . .Struct . . . .Struct::Tms .Symbol . . . .Thread . . . .ThreadGroup .Time . . . . . .TrueClass . 65165265465565665765865966066166266366466566628 S TANDARD L IBRARYAbbrev . . . .Base64 . . . .Benchmark . .BigDecimal . .CGI . . . . . .CGI::SessionComplex . . . .CSV . . . . . .Curses . . . .Date/DateTimeDBM . . . . . .Delegator . .Digest . . . .DL . . . . . . .dRuby . . . . .English . . . .Enumerator . .erb . . . . . .Etc . . . . . .expect . . . .Fcntl . . . . .FileUtils . .Find . . . . . .Forwardable .ftools . . . .GDBM . . . . . .Generator . .GetoptLong . .GServer . . . .Iconv . . . . .IO/Wait . . . .Prepared exclusively for Dr. Eugene Wallingford

CONTENTSIPAddr . . . .jcode . . . . .Logger . . . .Mail . . . . . .mathn . . . . .Matrix . . . .Monitor . . . .Mutex . . . . .Mutex m . . . .Net::FTP . . .Net::HTTP . .Net::IMAP . .Net::POP . . .Net::SMTP . .Net::Telnet .NKF . . . . . .Observable . .open-uri . . .Open3 . . . . .OpenSSL . . . .OpenStruct . .OptionParserParseDate . .Pathname . . .PP . . . . . . .PrettyPrint .Profile . . . .Profiler .PStore . . . .PTY . . . . . .Rational . . .readbytes . .Readline . . .Resolv . . . .REXML . . . . .Rinda . . . . .RSS . . . . . .Scanf . . . . .SDBM . . . . . .Set . . . . . .Shellwords . .Singleton . .SOAP . . . . . .Prepared exclusively for Dr. Eugene 698699700701702703704706707708709710711712713

CONTENTSSocket . . . .StringIO . . .StringScannerSync . . . . . .Syslog . . . .Tempfile . . .Test::Unit . .thread . . . .ThreadsWait .Time . . . . . .Timeout . . . .Tk . . . . . . .tmpdir . . . .Tracer . . . .TSort . . . . .un . . . . . . .URI . . . . . .WeakRef . . . .WEBrick . . . .Win32API . . .WIN32OLE . . .XMLRPC . . . .YAML . . . . . .Zlib . . . . . 751753754PART V—A PPENDIXESA S OCKET L IBRARYBasicSocketSocket . . .IPSocket . .TCPSocket .SOCKSSocketTCPServer .UDPSocket .UNIXSocket .UNIXServer .Prepared exclusively for Dr. Eugene Wallingford.

CONTENTSxivB MKMF R EFERENCEmkmf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .C S UPPORTWeb Sites . . . .Download Sites .Usenet NewsgroupMailing Lists . . .D B IBLIOGRAPHYPrepared exclusively for Dr. Eugene Wallingford.755755758758759759759761

List of 7.1027.1127.1227.1327.1427.1528.128.2Example variable and class names . . . . . . . . . . . .Character class abbreviations . . . . . . . . . . . . . . .Common comparison operators . . . . . . . . . . . . . .Two threads in a race condition . . . . . . . . . . . . . .Debugger commands . . . . . . . . . . . . . . . . . . .Environment variables used by Ruby . . . . . . . . . . .irb command-line options . . . . . . . . . . . . . . . . .Version operators . . . . . . . . . . . . . . . . . . . . .Command-line options for erb . . . . . . . . . . . . . .C/Ruby data type conversion functions and macros . . .General delimited input . . . . . . . . . . . . . . . . . .Substitutions in double-quoted strings . . . . . . . . . .Reserved words . . . . . . . . . . . . . . . . . . . . . .Ruby operators (high to low precedence) . . . . . . . . .Definition of the safe levels . . . . . . . . . . . . . . . .Class Array: pack directives . . . . . . . . . . . . . . .Class File: match-mode constants . . . . . . . . . . . .Class File: path separators . . . . . . . . . . . . . . . .Class File: open-mode constants . . . . . . . . . . . . .Class File: lock-mode constants . . . . . . . . . . . . .Class IO: mode strings . . . . . . . . . . . . . . . . . .Module Kernel: sprintf flag characters . . . . . . . .Module Kernel: sprintf field types . . . . . . . . . . .Module Kernel: file tests with a single argument . . . .Module Kernel: file tests with two arguments . . . . . .Class Numeric: methods and subclasses . . . . . . . . .Class Numeric: divmod, modulo, and remainder . . . .Class String: backslash sequences in substitution stringsClass String: unpack directives . . . . . . . . . . . . .Class Time: strftime directives . . . . . . . . . . . . .Class ERB: inline directives . . . . . . . . . . . . . . . .Class OptionParser: option definitions . . . . . . . . .Prepared exclusively for Dr. Eugene 7653691

List of 24.324.427.127.2Variables hold object references. . . . . . . . . .How arrays are indexed . . . . . . . . . . . . . .Ruby exception hierarchy . . . . . . . . . . . . .Roman numerals generation (with bugs) . . . . .Test::Unit assertions . . . . . . . . . . . . . . . .Sample irb session . . . . . . . . . . . . . . . . .Comparing variable access costs using benchmarkBrowse RDoc output for class counter . . . . . .Browse RDoc output when source has commentsUsing ri to read documentation . . . . . . . . . .Document for class Proc generated by RDoc/ri .Ruby source file documented with RDoc . . . . .C source file documented with RDoc . . . . . . .Sample program using RDoc::usage . . . . . . .Help generated by sample program . . . . . . . .MomLog package structure . . . . . . . . . . . .Sample CGI Form . . . . . . . . . . . . . . . . .Erb processing a file with loops . . . . . . . . . .Drawing on a Tk Canvas . . . . . . . . . . . . .Wrapping objects around C data types . . . . . .Building an extension . . . . . . . . . . . . . . .State transitions for boolean range . . . . . . . .A basic object, with its class and superclass . . .Adding a metaclass to Guitar . . . . . . . . . .Adding a virtual class to an object . . . . . . . .An included module and its proxy class . . . . .Standard exception hierarchy . . . . . . . . . . .Method#arity in action . . . . . . . . . . . . .Prepared exclusively for Dr. Eugene 98201202220225232248272283327363364367369441523

Foreword to theFirst EditionMan is driven to create; I know I really love to create things. And while I’m not goodat painting, drawing, or music, I can write software.Shortly after I was introduced to computers, I became interested in programming languages. I believed that an ideal programming language must be attainable, and I wantedto be the designer of it. Later, after gaining some experience, I realized that this kind ofideal, all-purpose language might be more difficult than I had thought. But I was stillhoping to design a language that would work for most of the jobs I did everyday. Thatwas my dream as a student.Years later I talked with colleagues about scripting languages, their power and possibility. As an object-oriented fan for more than fifteen years, it seemed to me that OOprogramming was very suitable for scripting too. I did some research on the ’net for awhile, but the candidates I found, Perl and Python, were not exactly what I was looking for. I wanted a language more powerful than Perl and more object-oriented thanPython.Then, I remembered my old dream and decided to design my own language. At first Iwas just toying around with it at work. But gradually it grew to be a tool good enoughto replace Perl. I named it Ruby—after the precious red stone—and released it to thepublic in 1995.Since then a lot of people have become interested in Ruby. Believe it or not, Ruby isactually more popular than Python in Japan right now. I hope that eventually it will bejust as well received all over the world.I believe that the purpose of life is, at least in part, to be happy. Based on this belief,Ruby is designed to make programming not only easy but also fun. It allows you toconcentrate on the creative side of programming, with less stress. If you don’t believeme, read this book and try Ruby. I’m sure you’ll find out for yourself.I’m very thankful to the people who have joined the Ruby community; they have helpedme a lot. I almost feel like Ruby is one of my children, but in fact, it is the result of thePrepared exclusively for D

The Pragmatic Programmers’Guide Second Edition Dave Thomas with Chad Fowler and Andy Hunt The PragmaticBookshelf Raleigh, North Carolina Dallas, Texas Prepared exclusively for Dr. Eugene Wallingford. Many of the designations used by manufacturers