Tải bản đầy đủ (.pdf) (1,325 trang)

Addison wesley the ruby way solutions and techniques in ruby programming 2nd edition nov 2006 ISBN 0672328844 (1)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.31 MB, 1,325 trang )

TheRubyWay:SolutionsandTechniquesinRuby
Programming,SecondEdition
ByHalFulton
...............................................
Publisher:AddisonWesleyProfessional
PubDate:October25,2006
PrintISBN-10:0-672-32884-4
PrintISBN-13:978-0-672-32884-8
Pages:888

TableofContents|Index

Rubyisanagileobject-orientedlanguage,borrowingsomeofthebestfeaturesfromLISP,
Smalltalk,Perl,CLU,andotherlanguages.Itspopularityhasgrowntremendouslyinthe
fiveyearssincethefirsteditionofthisbook.
TheRubyWaytakesa"how-to"approachtoRubyprogrammingwiththebulkofthe
materialconsistingofmorethan400examplesarrangedbytopic.Eachexampleanswers
thequestion"HowdoIdothisinRuby?"Workingalongwiththeauthor,youarepresented
withthetaskdescriptionandadiscussionofthetechnicalconstraints.Thisisfollowedbya
step-by-steppresentationofonegoodsolution.Alongtheway,theauthorprovides
detailedcommentaryandexplanationstoaidyourunderstanding.
Coverageincludes
•AnoverviewofRuby,explainingterminologyandbasicprinciples
•Operationsonlow-leveldatatypes(numbers,strings,regularexpressions,dates)
•Thenewregularexpressionengine(Oniguruma)
•Internationalization(I18N)andmessagecatalogsinRuby
•Operationsonhashes,arrays,andotherdatastructuressuchasstacks,trees,and
graphs
•WorkingwithgeneralI/O,files,andpersistentobjects
•DatabasecoverageincludingMySQL,SQLite,Oracle,DBI,andmore
•Ruby-specifictechniquesinOOPanddynamicprogramming


•GraphicalinterfacesinRuby(Tk,GTK+,Fox,andQt)
•WorkingwithRubythreadsforlightweightmultitasking


•EverydayscriptingandsystemadministrationinRuby
•Workingwithimagefiles,PDFs,YAML,XML,RSS,andAtom
•Testing,debugging,profiling,andpackagingRubycode
•Low-levelnetworkprogrammingandclient-serverinteraction
•WebdevelopmenttoolsincludingRails,Nitro,Wee,IOWA,andmore
•WorkingwithdistributedRuby,Rinda,andRing
•RubydevelopmenttoolssuchasIDEs,documentationtools,andmore
Thesourcecodeforthebookcanbedownloadedfromwww.rubyhacker.com
HalFultonhasworkedforover15yearswithvariousformsofUnix,includingAIX,Solaris,
andLinux.HewasfirstexposedtoRubyin1999,andin2001hebeganworkonthefirst
editionofthisbookthesecondRubybookpublishedintheEnglishlanguage.Hehas
attendednumerousRubyconferencesandhasgivenpresentationsatseveralofthose,
includingthefirstEuropeanRubyConference.
HehastwodegreesincomputersciencefromtheUniversityofMississippiandtaught
computerscienceforfouryearsbeforemovingtoAustin,Texastoworkasacontractorfor
variouscompanies,includingIBMAustin.HalcurrentlyworksatBroadwing
CommunicationsinAustin,Texas,maintainingalargedatawarehouseandrelatedtelecom
applications,workingdailywithC++,Oracle,and,ofcourse,Ruby.


TheRubyWay:SolutionsandTechniquesinRuby
Programming,SecondEdition
ByHalFulton
...............................................
Publisher:AddisonWesleyProfessional
PubDate:October25,2006

PrintISBN-10:0-672-32884-4
PrintISBN-13:978-0-672-32884-8
Pages:888

TableofContents|Index








































Copyright

Foreword
Acknowledgments
AbouttheAuthor
Introduction
Chapter1.RubyinReview
Section1.1.AnIntroductiontoObjectOrientation
Section1.2.BasicRubySyntaxandSemantics
Section1.3.OOPinRuby
Section1.4.DynamicAspectsofRuby
Section1.5.TrainingYourIntuition:ThingstoRemember
Section1.6.RubyJargonandSlang
Section1.7.Conclusion
Chapter2.WorkingwithStrings
Section2.1.RepresentingOrdinaryStrings

Section2.2.RepresentingStringswithAlternateNotations
Section2.3.UsingHere-Documents
Section2.4.FindingtheLengthofaString
Section2.5.ProcessingaLineataTime
Section2.6.ProcessingaByteataTime
Section2.7.PerformingSpecializedStringComparisons


















































































Section2.8.TokenizingaString
Section2.9.FormattingaString
Section2.10.UsingStringsAsIOObjects
Section2.11.ControllingUppercaseandLowercase

Section2.12.AccessingandAssigningSubstrings
Section2.13.SubstitutinginStrings
Section2.14.SearchingaString
Section2.15.ConvertingBetweenCharactersandASCIICodes
Section2.16.ImplicitandExplicitConversion
Section2.17.AppendinganItemOntoaString
Section2.18.RemovingTrailingNewlinesandOtherCharacters
Section2.19.TrimmingWhitespacefromaString
Section2.20.RepeatingStrings
Section2.21.EmbeddingExpressionsWithinStrings
Section2.22.DelayedInterpolationofStrings
Section2.23.ParsingComma-SeparatedData
Section2.24.ConvertingStringstoNumbers(DecimalandOtherwise)
Section2.25.EncodingandDecodingrot13Text
Section2.26.EncryptingStrings
Section2.27.CompressingStrings
Section2.28.CountingCharactersinStrings
Section2.29.ReversingaString
Section2.30.RemovingDuplicateCharacters
Section2.31.RemovingSpecificCharacters
Section2.32.PrintingSpecialCharacters
Section2.33.GeneratingSuccessiveStrings
Section2.34.Calculatinga32-BitCRC
Section2.35.CalculatingtheMD5HashofaString
Section2.36.CalculatingtheLevenshteinDistanceBetweenTwoStrings
Section2.37.EncodingandDecodingbase64Strings
Section2.38.EncodingandDecodingStrings(uuencode/uudecode)
Section2.39.ExpandingandCompressingTabCharacters
Section2.40.WrappingLinesofText
Section2.41.Conclusion

Chapter3.WorkingwithRegularExpressions
Section3.1.RegularExpressionSyntax
Section3.2.CompilingRegularExpressions
Section3.3.EscapingSpecialCharacters
Section3.4.UsingAnchors

















































































Section3.5.UsingQuantifiers
Section3.6.PositiveandNegativeLookahead
Section3.7.AccessingBackreferences
Section3.8.UsingCharacterClasses
Section3.9.ExtendedRegularExpressions
Section3.10.MatchingaNewlinewithaDot

Section3.11.UsingEmbeddedOptions
Section3.12.UsingEmbeddedSubexpressions
Section3.13.RubyandOniguruma
Section3.14.AFewSampleRegularExpressions
Section3.15.Conclusion
Chapter4.InternationalizationinRuby
Section4.1.BackgroundandTerminology
Section4.2.CodinginaPost-ASCIIWorld
Section4.3.UsingMessageCatalogs
Section4.4.Conclusion
Chapter5.PerformingNumericalCalculations
Section5.1.RepresentingNumbersinRuby
Section5.2.BasicOperationsonNumbers
Section5.3.RoundingFloatingPointValues
Section5.4.ComparingFloatingPointNumbers
Section5.5.FormattingNumbersforOutput
Section5.6.FormattingNumberswithCommas
Section5.7.WorkingwithVeryLargeIntegers
Section5.8.UsingBigDecimal
Section5.9.WorkingwithRationalValues
Section5.10.MatrixManipulation
Section5.11.WorkingwithComplexNumbers
Section5.12.Usingmathn
Section5.13.FindingPrimeFactorization,GCD,andLCM
Section5.14.WorkingwithPrimeNumbers
Section5.15.ImplicitandExplicitNumericConversion
Section5.16.CoercingNumericValues
Section5.17.PerformingBit-levelOperationsonNumbers
Section5.18.PerformingBaseConversions
Section5.19.FindingCubeRoots,FourthRoots,andsoon

Section5.20.DeterminingtheArchitecture'sByteOrder
Section5.21.NumericalComputationofaDefiniteIntegral
Section5.22.TrigonometryinDegrees,Radians,andGrads
















































































Section5.23.MoreAdvancedTrigonometry
Section5.24.FindingLogarithmswithArbitraryBases
Section5.25.FindingtheMean,Median,andModeofaDataSet
Section5.26.VarianceandStandardDeviation
Section5.27.FindingaCorrelationCoefficient
Section5.28.GeneratingRandomNumbers
Section5.29.CachingFunctionswithmemoize
Section5.30.Conclusion
Chapter6.SymbolsandRanges

Section6.1.Symbols
Section6.2.Ranges
Section6.3.Conclusion
Chapter7.WorkingwithTimesandDates
Section7.1.DeterminingtheCurrentTime
Section7.2.WorkingwithSpecificTimes(Post-epoch)
Section7.3.DeterminingtheDayoftheWeek
Section7.4.DeterminingtheDateofEaster
Section7.5.FindingtheNthWeekdayinaMonth
Section7.6.ConvertingBetweenSecondsandLargerUnits
Section7.7.ConvertingToandFromtheEpoch
Section7.8.WorkingwithLeapSeconds:Don't!
Section7.9.FindingtheDayoftheYear
Section7.10.ValidatingaDate/Time
Section7.11.FindingtheWeekoftheYear
Section7.12.DetectingLeapYears
Section7.13.ObtainingtheTimeZone
Section7.14.WorkingwithHoursandMinutesOnly
Section7.15.ComparingDate/TimeValues
Section7.16.AddingIntervalstoDate/TimeValues
Section7.17.ComputingtheDifferenceinTwoDate/TimeValues
Section7.18.WorkingwithSpecificDates(Pre-epoch)
Section7.19.InterconvertingBetweenTime,Date,andDateTime
Section7.20.RetrievingaDate/TimeValuefromaString
Section7.21.FormattingandPrintingDate/TimeValues
Section7.22.TimeZoneConversions
Section7.23.DeterminingtheNumberofDaysinaMonth
Section7.24.DividingaMonthintoWeeks
Section7.25.Conclusion
Chapter8.Arrays,Hashes,andOtherEnumerables














































































Section8.1.WorkingwithArrays
Section8.2.WorkingwithHashes
Section8.3.EnumerablesinGeneral
Section8.4.Conclusion
Chapter9.MoreAdvancedDataStructures
Section9.1.WorkingwithSets
Section9.2.WorkingwithStacksandQueues
Section9.3.WorkingwithTrees
Section9.4.WorkingwithGraphs
Section9.5.Conclusion
Chapter10.I/OandDataStorage
Section10.1.WorkingwithFilesandDirectories
Section10.2.PerformingHigher-LevelDataAccess
Section10.3.UsingKirbyBase
Section10.4.ConnectingtoExternalDatabases

Section10.5.Conclusion
Chapter11.OOPandDynamicFeaturesinRuby
Section11.1.EverydayOOPTasks
Section11.2.MoreAdvancedTechniques
Section11.3.WorkingwithDynamicFeatures
Section11.4.Conclusion
Chapter12.GraphicalInterfacesforRuby
Section12.1.Ruby/Tk
Section12.2.Ruby/GTK2
Section12.3.FXRuby(FOX)
Section12.4.QtRuby
Section12.5.OtherGUIToolkits
Section12.6.Conclusion
Chapter13.ThreadsinRuby
Section13.1.CreatingandManipulatingThreads
Section13.2.SynchronizingThreads
Section13.3.Conclusion
Chapter14.ScriptingandSystemAdministration
Section14.1.RunningExternalPrograms
Section14.2.Command-LineOptionsandArguments
Section14.3.TheShellLibrary
Section14.4.AccessingEnvironmentVariables
Section14.5.ScriptinginMicrosoftWindows
Section14.6.TheWindowsOne-ClickInstaller














































































Section14.7.LibrariesYouNeedtoKnowAbout
Section14.8.WorkingwithFiles,Directories,andTrees
Section14.9.MiscellaneousScriptingTasks
Section14.10.Conclusion
Chapter15.RubyandDataFormats
Section15.1.ParsingXMLwithREXML
Section15.2.WorkingwithRSSandAtom
Section15.3.ManipulatingImageDatawithRMagick
Section15.4.CreatingPDFDocumentswithPDF::Writer
Section15.5.Conclusion
Chapter16.TestingandDebugging
Section16.1.TestingwithTest::Unit
Section16.2.TheZenTestTools
Section16.3.UsingtheRubyDebugger
Section16.4.UsingirbAsaDebugger
Section16.5.MeasuringCodeCoverage
Section16.6.MeasuringPerformance
Section16.7.PrettyprintingObjects
Section16.8.Conclusion
Chapter17.PackagingandDistributingCode
Section17.1.UsingRDoc

Section17.2.InstallationandPackaging
Section17.3.RubyForgeandtheRAA
Section17.4.Conclusion
Chapter18.NetworkProgramming
Section18.1.NetworkServers
Section18.2.NetworkClients
Section18.3.Conclusion
Chapter19.RubyandWebApplications
Section19.1.CGIProgrammingwithRuby
Section19.2.UsingFastCGI
Section19.3.RubyonRails
Section19.4.WebDevelopmentwithNitro
Section19.5.AnIntroductiontoWee
Section19.6.WebDevelopmentwithIOWA
Section19.7.RubyandtheWebServer
Section19.8.Conclusion
Chapter20.DistributedRuby
Section20.1.AnOverview:Usingdrb














































Section20.2.CaseStudy:AStockTickerSimulation
Section20.3.Rinda:ARubyTuplespace
Section20.4.ServiceDiscoverywithDistributedRuby
Section20.5.Conclusion
Chapter21.RubyDevelopmentTools
Section21.1.UsingRubyGems
Section21.2.UsingRake
Section21.3.Usingirb
Section21.4.TheriUtility
Section21.5.EditorSupport
Section21.6.IntegratedDevelopmentEnvironments
Section21.7.Conclusion
Chapter22.TheRubyCommunity
Section22.1.WebResources
Section22.2.NewsgroupandMailingLists
Section22.3.BlogsandOnlineMagazines
Section22.4.RubyChangeRequests
Section22.5.IRCChannels
Section22.6.RubyConferences
Section22.7.LocalRubyGroups
Section22.8.Conclusion
Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas

awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin
connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheUnitedStatespleasecontact:
InternationalSales

VisitusontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData:
Fulton,HalEdwin,1961-


TheRubyway:solutionsandtechniquesinRubyprogramming/HalFulto
-2nded.
p.cm.
Includesindex.
ISBN0-672-32884-4(pbk.:alk.paper)1.Objectorientedprogramming(Computerscience)2.Ruby

(Computerprogramlanguage)I.Title.

QA76.64.F852006
005.1'17dc22

Copyright©2007PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
TextprintedintheUnitedStatesonrecycledpaperatRR
DonnelleyinCrawfordsville,Indiana.
Firstprinting,October2006

Dedication
Tomyparents,withoutwhomIwouldnotbepossible



"Amongotherthings,thisbookexcelsatexplaining
metaprogramming,oneofthemostinterestingaspectsof
Ruby.ManyoftheearlyideasforRailswereinspiredby

thefirstedition,especiallywhatisnowchapter11.Itputs
youonarollercoasterridebetween'HowcouldIuse
this?'to'Thisissocool!'Onceyougetonthatroller
coaster,there'snoturningback."
DavidHeinemeierHansson,
CreatorofRubyonRails,
Partnerwith37signals
"Theappearanceofthesecondeditionofthisclassicbook
isanexcitingeventforRubyistsandforloversofsuperb
technicalwritingingeneral.HalFultonbringsalively
eruditionandanengaging,lucidstyletobearona
thoroughandmeticulouslyexactexpositionofRuby.You
palpablyfeelthepresenceofateacherwhoknowsa
tremendousamountandreallywantstohelpyouknowit
too."
DavidAlanBlack,
AuthorofRubyforRails
"Thisisanexcellentresourceforgaininginsightintohow
andwhyRubyworks.Assomeonewhohasworkedwith
Rubyforseveralyears,Istillfounditfullofnewtricksand
techniques.It'saccessiblebothasastraightreadandasa
referencethatonecandipintoandlearnsomethingnew."
ChetHendrickson,
Agilesoftwarepioneer


"IusethefirsteditionofHal'sbookfrequently,tolearn
aboutdetailsandstyleinRuby,becauseitcoversmany
topicsIcanfindnowhereelse.Theneweditioniseven
morecomprehensiveandwillbeevenmorevaluable."

RonJeffries,
Agileauthorandspeaker
"Ruby'sawonderfullanguagebutsometimesyoujustwant
togetsomethingdone.Hal'sbookgivesyouthesolution
andteachesagoodbitaboutwhythatsolutionisgood
Ruby."
MartinFowler
ChiefScientist,ThoughtWorks
AuthorofPatternsofEnterprise
ApplicationArchitecture




Foreword
ForewordtotheSecondEdition
InancientChina,people,especiallyphilosophers,thoughtthat
somethingwashiddenbehindtheworldandeveryexistence.It
canneverbetold,norexplained,nordescribedinconcrete
words.TheycalleditTaoinChineseandDoinJapanese.Ifyou
translateitintoEnglish,itisthewordforWay.ItistheDoin
Judo,Kendo,Karatedo,andAikido.Theyarenotonlymartial
arts,buttheyalsoincludeaphilosophyandawayoflife.
Likewise,Rubytheprogramminglanguagehasitsphilosophy
andwayofthinking.Itenlightenspeopletothinkdifferently.It
helpsprogrammershavemorefunintheirwork.Itisnot
becauseRubyisfromJapanbutbecauseprogrammingisan
importantpartofthehumanbeing(well,atleastsomehuman
beings),andRubyisdesignedtohelppeoplehaveabetterlife.
Asalways,"Tao"isdifficulttodescribe.Ifeelitbuthavenever

triedtoexplainitinwords.It'sjusttoodifficultforme,evenin
Japanese,mynativetongue.ButaguynamedHalFultontried,
andhisfirsttry(thefirsteditionofthisbook)wasprettygood.
ThissecondversionofhistrialtodescribetheTaoofRuby
becomesevenbetterwithhelpfrommanypeopleintheRuby
community.AsRubybecomesmorepopular(partlyduetoRuby
onRails),itbecomesmoreimportanttounderstandthesecret
ofprogrammers'productivity.Ihopethisbookhelpsyouto
becomeanefficientprogrammer.
HappyHacking.
Yukihiro"Matz"Matsumoto
August2006,Japan


ForewordtoFirstEdition
ShortlyafterIfirstmetwithcomputersintheearly80sI
becameinterestedinprogramminglanguages.SincethenI
havebeena"languagegeek."Ithinkthereasonforthis
interestisthatprogramminglanguagesarewaystoexpress
humanthought.Theyarefundamentallyhuman-oriented.
Despitethisfact,programminglanguageshavetendedtobe
machine-oriented.Manylanguagesweredesignedforthe
convenienceofthecomputer.
Butascomputersbecamemorepowerfulandlessexpensive,
thissituationgraduallychanged.Forexample,lookat
structuredprogramming.Machinesdonotcarewhether
programsarestructuredwell;theyjustexecutethembitbybit.
Structuredprogrammingisnotformachines,butforhumans.
Thisistrueofobject-orientedprogrammingaswell.
Thetimeforlanguagedesignfocusingonhumanshasbeen

coming.
In1993,Iwastalkingwithacolleagueaboutscripting
languages,abouttheirpowerandfuture.Ifeltscriptingtobe
thewayfutureprogrammingshouldbehuman-oriented.
ButIwasnotsatisfiedwithexistinglanguagessuchasPerland
Python.IwantedalanguagethatwasmorepowerfulthanPerl
andmoreobject-orientedthanPython.Icouldn'tfindtheideal
language,soIdecidedtomakemyown.
Rubyisnotthesimplestlanguage,butthehumansoulisnot
simpleinitsnaturalstate.Itlovessimplicityandcomplexityat
thesametime.Itcan'thandletoomanycomplexthings,nor
toomanysimplethings.It'samatterofbalance.


Sotodesignahuman-orientedlanguage,Ruby,Ifollowedthe
PrincipleofLeastSurprise.Iconsiderthateverythingthat
surprisesmelessisgood.AsaresultIfeelanaturalfeeling,
evenakindofjoy,whenprogramminginRuby.Andsincethe
firstreleaseofRubyin1995,manyprogrammersworldwide
haveagreedwithmeaboutthejoyofRubyprogramming.
AsalwaysI'dliketoexpressmygreatestappreciationtothe
peopleintheRubycommunity.TheyaretheheartofRuby's
success.
Iamalsothankfultotheauthorofthisbook,HalE.Fulton,for
declaringtheRubyWaytohelppeople.
ThisbookexplainsthephilosophybehindRuby,distilledfrom
mybrainandtheRubycommunity.Iwonderhowitcanbe
possibleforHaltoreadmymindtoknowandrevealthissecret
oftheRubyWay.Ihavenevermethimfacetoface;Ihopeto
meethimsoon.

IhopethisbookandRubybothservetomakeyour
programmingfunandhappy.
Yukihiro"Matz"Matsumoto
September2001,Japan




Acknowledgments
AcknowledgmentsfortheSecondEdition
Commonsensesaysthatasecondeditionwillonlyrequirehalf
asmuchworkasthefirsteditionrequired.Commonsenseis
wrong.
Eventhoughalargepartofthisbookcamedirectlyfromthe
firstedition,eventhatparthadtobetweakedandtuned.Every
singlesentenceinthisbookhadtopassthrough(atthevery
least)afilterthatasked:Iswhatwastruein2001stilltruein
2006?Andthat,ofcourse,wasonlythebeginning.
Inshort,Iputinmanyhundredsofhoursofworkonthis
secondeditionnearlyasmuchtimeasonthefirst.AndyetIam
"onlytheauthor."
Abookispossibleonlythroughtheteamworkofmanypeople.
Onthepublisher'sside,IowethankstoDebraWilliamsCauley,
SonglinQiu,andMandieFrankfortheirhardworkandinfinite
patience.ThanksgotoGeneilBreezeforhertireless
copyeditingandpickingbitsoflintfrommyEnglish.Thereare
alsoothersIcan'tnamebecausetheirworkwascompletely
behindthescenes,andInevertalkedwiththem.
TechnicaleditingwasdoneprimarilybyShashankDateand
FrancisHwang.Theydidagreatjob,andIappreciateit.Errors

thatslippedthrougharemyresponsibility,ofcourse.
Thanksgotothepeoplewhosuppliedexplanations,wrote
samplecode,andanswerednumerousquestionsforme.These
includeMatzhimself(YukihiroMatsumoto),DaveThomas,
ChristianNeukirchen,ChadFowler,CurtHibbs,DanielBerger,
ArminRoehrl,StefanSchmiedl,JimWeirich,RyanDavis,Jenny


W.,JimFreeze,LyleJohnson,MartinDeMello,MattLawrence,
theinfamouswhytheluckystiff,RonJeffries,TimHunter,Chet
Hendrickson,NathanielTalbott,andBilKleb.
Specialthanksgoestotheheaviercontributors.Andrew
Johnsongreatlyenhancedmyregularexpressionknowledge.
PaulBattleymadegreatcontributionstotheinternationalization
chapter.MasaoMutohaddedtothatsamechapterandalso
contributedmaterialonGTK.AustinZieglertaughtmethe
secretsofwritingPDFfiles.CalebTennisaddedtotheQt
material.EricHodeladdedtotheRindaandRingmaterial,and
JamesBrittcontributedheavilytothewebdevelopment
chapter.
ThanksandappreciationagainmustgotoMatz,notonlyforhis
assistancebutforcreatingRubyinthefirstplace.Domoarigato
gozaimasu!
AgainIhavetothankmyparents.Theyhaveencouragedme
withoutceasingandarelookingforwardtoseeingthisbook.I
willmakeprogrammersofthembothyet.
Andonceagain,IhavetothankalloftheRubycommunityfor
theirtirelessenergy,productivity,andcommunityspirit.I
particularlythankthereadersofthisbook(inbotheditions).I
hopeyoufinditinformative,useful,andperhapseven

entertaining.

AcknowledgmentsfortheFirstEdition
Writingabookistrulyateameffort;thisisafactIcouldnot
fullyappreciateuntilIwroteonemyself.Irecommendthe
experience,althoughitisahumblingone.Itisasimpletruth
thatwithouttheassistanceofmanyotherpeople,thisbook
wouldnothaveexisted.
ThanksandappreciationmustfirstgotoMatz(Yukihiro


Matsumoto),whocreatedtheRubylanguageinthefirstplace.
Domoarigatogozaimasu!
ThanksgoestoConradSchneikerforconceivingtheoverallidea
forthebookandhelpingtocreateitsoverallstructure.Healso
didmetheserviceofintroducingmetotheRubylanguagein
1999.
Severalindividualshavecontributedmaterialtothebodyofthe
book.TheforemostofthesewasGuyHurst,whowrote
substantialpartsoftheearlierchaptersaswellastwoofthe
appendices.Hisassistancewasabsolutelyinvaluable.
Thanksalsogoestotheothercontributors,whomI'llnamein
noparticularorder.KevinSmithdidagreatjobontheGTK
sectionofChapter6,savingmefromapotentiallysteep
learningcurveonatightschedule.PatrickLogan,inthesame
chapter,shedlightonthemysteriesoftheFOXGUI.Chad
Fowler,inChapter9,plumbedthedepthsofXMLandalso
contributedtotheCGIsection.
Thankstothosewhoassistedinproofreadingorreviewingorin
othermiscellaneousways:DonMuchow,MikeStok,Miho

Ogishima,andothersalreadymentioned.ThankstoDavid
Eppstein,themathematicsprofessor,foransweringquestions
aboutgraphtheory.
OneofthegreatthingsaboutRubyisthesupportofthe
community.Thereweremanyonthemailinglistandthe
newsgroupwhoansweredquestionsandgavemeideasand
assistance.Againinnoparticularorder,theseareDave
Thomas,AndyHunt,Hee-SobPark,MikeWilson,AviBryant,
YasushiShoji("Yashi"),ShugoMaeda,JimWeirich,"arton,"and
MasakiSuketa.I'msorrytosayIhaveprobablyoverlooked
someone.
Tostatetheobvious,abookwouldneverbepublishedwithout
apublisher.Manypeoplebehindthescenesworkedhardto


producethisbook;primarilyIhavetothankWilliamBrown,
whoworkedcloselywithmeandwasaconstantsourceof
encouragement;andScottMeyer,whodelveddeeplyintothe
detailsofputtingthematerialtogether.OthersIcannoteven
namebecauseIhaveneverheardofthem.Youknowwhoyou
are.
Ihavetothankmyparents,whowatchedthisprojectfroma
distance,encouragedmealongtheway,andevenbotheredto
learnalittlebitofcomputerscienceformysake.
Awriterfriendofmineoncetoldme,"Ifyouwriteabookand
nobodyreadsit,youhaven'treallywrittenabook."So,finally,I
wanttothankthereader.Thisbookisforyou.Ihopeitisof
somevalue.





AbouttheAuthor
HalFultonhastwodegreesincomputersciencefromthe
UniversityofMississippi.Hetaughtcomputerscienceforfour
yearsatthecommunitycollegelevelbeforemovingtoAustin,
Texas,foraseriesofcontracts(mainlyatIBMAustin).Hehas
workedformorethan15yearswithvariousformsofUNIX,
includingAIX,Solaris,andLinux.HewasfirstexposedtoRuby
in1999,andin2001hebeganworkonthefirsteditionofthis
book,whichwasthesecondRubybookintheEnglishlanguage.
HehasattendedsixRubyconferencesandhasgiven
presentationsatfourofthose,includingthefirstEuropeanRuby
ConferenceinKarlsruhe,Germany.Hecurrentlyworksat
BroadwingCommunicationsinAustin,Texas,workingonalarge
datawarehouseandrelatedtelecomapplications.Heworks
dailywithC++,Oracle,andofcourse,Ruby.
HalisstillactivedailyontheRubymailinglistandIRCchannel,
andhasseveralRubyprojectsinprogress.Heisamemberof
theACMandtheIEEEComputerSociety.Inhispersonallife,he
enjoysmusic,reading,writing,art,andphotography.Heisa
memberoftheMarsSocietyandisaspaceenthusiastwho
wouldlovetogointospacebeforehedies.HelivesinAustin,
Texas.


Introduction
ThewaythatcanbenamedisnotthetrueWay.
LaoTse,TaoTeChing
ThetitleofthisbookisTheRubyWay.Thisisatitlethatbegs

foradisclaimer.
Ithasbeenmyaimtoalignthisbookwiththephilosophyof
RubyaswellasIcould.Thathasalsobeentheaimoftheother
contributors.Creditforsuccessmustbesharedwiththese
others,buttheblameforanymistakesmustrestsolelywith
me.
Ofcourse,Ican'tpresumetotellyouwithexactnesswhatthe
spiritofRubyisallabout.ThatisprimarilyforMatztosay,and
Ithinkevenhewouldhavedifficultycommunicatingallofitin
words.
Inshort,TheRubyWayisonlyabook;buttheRubyWayisthe
provinceofthelanguagecreatorandthecommunityasa
whole.Thisissomethingdifficulttocaptureinabook.
StillIhavetriedinthisintroductiontopindownalittleofthe
ineffablespiritofRuby.ThewisestudentofRubywillnottakeit
astotallyauthoritative.
Beawarethatthisisasecondedition.Manythingshavestayed
thesame,butmanythingshavechanged.Mostofthis
introductionhasbeenpreserved,butyouwillwanttovisitthe
upcomingsection,"AbouttheSecondEdition,"whereI
summarizethechangesandthenewmaterial.

AbouttheSecondEdition


Everythingchanges,andRubyisnoexception.AsIwritethis
introductioninAugust2006,thefirsteditionofthisbookis
nearlyfiveyearsold.Itiscertainlytimeforanupdate.
Therearemanychangesandmuchnewmaterialinthisedition.
TheoldChapter4("SimpleDataTasks")isnowsplitintosix

chapters,twoofwhich("RangesandSymbols"and
"InternationalizationinRuby")aretotallynew;theotherfour
alsohavenewexamplesandcommentaryaddedtothem.The
coverageofregualrexpressionsisparticularlyexpanded,
coveringnotonly"classic"regexesbutthenewerOniguruma
regexengine.
Chapters8and9wereoriginallyonechapter.Thiswassplitas
materialwasaddedandthechaptergrewtoobig.
Inthesameway,thecurrentchapters18,19,and20grewout
oftheoldchapter9asmaterialwasadded.Theappendices
weredeletedtomakeroomformorematerial.
Othernewchaptersare:
Chapter15,"RubyandDataFormats."ThiscoversXML,
RSS,imagefiles,writingPDFfiles,andmore.
Chapter16,"TestingandDebugging."Thisdealswithunit
testing,profiling,debugging,codecoverage,andsimilar
topics.
Chapter17,"PackagingandDistributingCode."Thischapter
coverstheuseofsetup.rb,thecreationofRubyGems,and
more.
Chapter21,"RubyDevelopmentTools."Thisoffersalookat
RubyeditorsupportandIDEs,theriutility,andRubyGems
fromauser'sperspective.


Chapter22,"TheRubyCommunity."Thischapter
summarizesallthemajorwebsites,mailinglists,
newsgroups,conferences,IRCchannels,andmore.
Inalargersense,everysinglechapterinthisbookis"new."I
haverevisedandupdatedeveryoneofthem,makinghundreds

ofminorchangesanddozensofmajorchanges.Ideleteditems
thatwereobsoleteoroflesserimportance;Ichangedmaterial
tofitchangesinRubyitself;andIaddednewexamplesand
commentarytoeverychapter.
Youmaywonderwhathasbeenaddedtotheoldchapters.
SomeofthehighlightsaretheOnigurumacoverage,whichI
alreadymentioned;coverageofmathlibrariesandclassessuch
asBigDecimal,mathn,andmatrix;andnewclassessuchasSetand
DateTime.
InChapter10,"I/OandDataStorage,"Iaddedmaterialon
readpartial,onnonblockingI/O,andontheStringIOclass.Ialso
addedmaterialonCSV,YAML,andKirbyBase.Inthedatabase
portionofthatsamechapterIaddedOracle,SQLite,DBI,anda
discussionofObject-RelationalMappers(ORMs).
Chapter11,"OOPandDynamicFeaturesinRuby,"nowincludes
morerecentadditionstoRubysuchasinitialize_copy,const_get,
const_missing,anddefine_method.Ialsoaddedcoverageof
delegationandforwardingtechniques.
AllofChapter12,"GraphicalInterfacesforRuby,"hadtobe
revised(especiallytheGTKandFoxsections).TheQtRuby
sectionistotallynew.
Chapter14,"ScriptingandSystemAdministration,"now
discussestheWindowsone-clickinstallerandafewsimilar
packages.Italsohasseveralimprovementsintheexample
code.


Chapter18,"NetworkProgramming,"nowhasasectionon
emailattachmentsandanothernewsectiononinteractingwith
anIMAPserver.ItalsohascoverageoftheOpenURIlibrary.

Chapter19,"RubyandWebApplications,"nowcoversRubyon
Rails,Nitro,Wee,IOWA,andotherwebtools.Italsohas
coverageofWEBrickandsomecoverageofMongrel.
Chapter20,"DistributedRuby,"hasnewmaterialexplaining
Rinda,theRubytuplespaceimplementation.ItalsocoversRing,
whichiscloselyrelated.
Werealltheseadditionsnecessary?Iassureyoutheywere.
Fortherecord,TheRubyWaywasthesecondRubybookinthe
Englishlanguage(followingthefamous"Pickaxe,"or
ProgrammingRuby,byDaveThomasandAndyHunt).Itwas
carefullydesignedtobecomplementarytothatbookrather
thanoverlappingit;thisisalargepartofthereasonforits
popularity.
WhenIbeganwritingthefirstedition,therewasno
internationalRubyconference.TherewasnoRubyForge,no
ruby-doc.org,andnorubygarden.orgwiki.Inessencetherewas
littleontheWebbesidesthemainRubysite.TheRuby
ApplicationArchivehadafewhundredentriesinit.
Atthattime,fewpublications(onlineoroff)seemedtoknowof
Ruby'sexistence.AnytimeanarticlewaspublishedaboutRuby,
itwascauseforustotakenotice;itwasannouncedonthe
mailinglistanddiscussedthere.
ManycommonRubytoolsandlibrariesalsodidnotexist.There
wasnoRDoc;therewasnoREXMLtoparseXML;themath
librarywasconsiderablylessrichthanitisnow.Database
supportwasspotty,andtherewasnoODBC.Tkwasbyfarthe
mostusedGUItoolkit.Themostcommonwayofdoingweb
developmentwasthelow-levelCGIlibrary.



×