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

0321714636 {3D86EDC2} the ruby way (3rd ed ) fulton arko 2015 03 13

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 (30.28 MB, 1,832 trang )


AboutThiseBook
ePUBisanopen,industry-standardformatforeBooks.However,supportofePUBand
itsmanyfeaturesvariesacrossreadingdevicesandapplications.Useyourdeviceorapp
settingstocustomizethepresentationtoyourliking.Settingsthatyoucancustomizeoften
includefont,fontsize,singleordoublecolumn,landscapeorportraitmode,andfigures
thatyoucanclickortaptoenlarge.Foradditionalinformationaboutthesettingsand
featuresonyourreadingdeviceorapp,visitthedevicemanufacturer’sWebsite.
Manytitlesincludeprogrammingcodeorconfigurationexamples.Tooptimizethe
presentationoftheseelements,viewtheeBookinsingle-column,landscapemodeand
adjustthefontsizetothesmallestsetting.Inadditiontopresentingcodeand
configurationsinthereflowabletextformat,wehaveincludedimagesofthecodethat
mimicthepresentationfoundintheprintbook;therefore,wherethereflowableformat
maycompromisethepresentationofthecodelisting,youwillseea“Clickheretoview
codeimage”link.Clickthelinktoviewtheprint-fidelitycodeimage.Toreturntothe
previouspageviewed,clicktheBackbuttononyourdeviceorapp.


THERUBYWAY
ThirdEdition
HalFulton
withAndréArko

UpperSaddleRiver,NJ•Boston•Indianapolis•SanFrancisco
NewYork•Toronto•Montreal•London•Munich•Paris•Madrid
CapeTown•Sydney•Tokyo•Singapore•MexicoCity


Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearinthisbook,andthe
publisherwasawareofatrademarkclaim,thedesignationshavebeenprintedwithinitial


capitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakeno
expressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsor
omissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnection
withorarisingoutoftheuseoftheinformationorprogramscontainedherein.
Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsalesopportunities
(whichmayincludeelectronicversions;customcoverdesigns;andcontentparticularto
yourbusiness,traininggoals,marketingfocus,orbrandinginterests),pleasecontactour
corporatesalesdepartmentator(800)382-3419.
Forgovernmentsalesinquiries,pleasecontact
ForquestionsaboutsalesoutsidetheU.S.,pleasecontact
VisitusontheWeb:informit.com/aw
LibraryofCongressControlNumber:2014945504
Copyright©2015PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotected
bycopyright,andpermissionmustbeobtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissioninanyformorbyanymeans,
electronic,mechanical,photocopying,recording,orlikewise.Toobtainpermissiontouse
materialfromthiswork,pleasesubmitawrittenrequesttoPearsonEducation,Inc.,
PermissionsDepartment,OneLakeStreet,UpperSaddleRiver,NewJersey07458,oryou
mayfaxyourrequestto(201)236-3290.
ISBN-13:978-0-321-71463-3
ISBN-10:0-321-71463-6
TextprintedintheUnitedStatesonrecycledpaperatRRDonnelleyinCrawfordsville,
Indiana
Firstprinting:March2015
Editor-in-Chief
MarkTaub
ExecutiveEditor
DebraWilliams-Cauley

DevelopmentEditor
SonglinQiu
ManagingEditor
KristyHart
ProjectEditor
AndyBeaster


CopyEditor
BartReed
Indexer
KenJohnson
Proofreader
SarahKearns
CoverDesigner
ChutiPrasertsith
SeniorCompositor
GloriaSchurick


PraiseforTheRubyWay,ThirdEdition
“Stickingtoitstriedandtestedformulaofcuttingrighttothetechniquesthemodern
dayRubyistneedstoknow,thelatesteditionofTheRubyWaykeepsitsstrong
reputationgoingforthelatestgenerationoftheRubylanguage.”
PeterCooper
EditorofRubyWeekly
“Theauthors’excellentworkandmeticulousattentiontodetailcontinuesinthislatest
update;thisbookremainsanoutstandingreferenceforthebeginningRuby
programmer—aswellastheseasoneddeveloperwhoneedsaquickrefreshonRuby.
HighlyrecommendedforanyoneinterestedinRubyprogramming.”

KelvinMeeks
EnterpriseArchitect


PraiseforPreviousEditionsofTheRubyWay
“Amongotherthings,thisbookexcelsatexplainingmetaprogramming,oneofthe
mostinterestingaspectsofRuby.ManyoftheearlyideasforRailswereinspiredby
thefirstedition,especiallywhatisnowChapter11.Itputsyouonarollercoasterride
between‘HowcouldIusethis?’and‘Thisissocool!’Onceyougetonthat
rollercoaster,there’snoturningback.”
DavidHeinemeierHansson
CreatorofRubyonRails,
FounderatBasecamp
“Theappearanceofthesecondeditionofthisclassicbookisanexcitingeventfor
Rubyists—andforloversofsuperbtechnicalwritingingeneral.HalFultonbringsa
livelyeruditionandanengaging,lucidstyletobearonathoroughandmeticulously
exactexpositionofRuby.Youpalpablyfeelthepresenceofateacherwhoknowsa
tremendousamountandreallywantstohelpyouknowittoo.”
DavidAlanBlack
AuthorofTheWell-GroundedRubyist
“ThisisanexcellentresourceforgaininginsightintohowandwhyRubyworks.As
someonewhohasworkedwithRubyforseveralyears,Istillfounditfullofnew
tricksandtechniques.It’saccessiblebothasastraightreadandasareferencethat
onecandipintoandlearnsomethingnew.”
ChetHendrickson
Agilesoftwarepioneer
“Ruby’sawonderfullanguage—butsometimesyoujustwanttogetsomethingdone.
Hal’sbookgivesyouthesolutionandteachesagoodbitaboutwhythatsolutionis
goodRuby.”
MartinFowler

ChiefScientist,ThoughtWorks
AuthorofPatternsofEnterprise
ApplicationArchitecture


Tomyparents,withoutwhomIwouldnotbepossible
—Hal


Contents
Foreword
Acknowledgments
AbouttheAuthors
Introduction
1RubyinReview
1.1AnIntroductiontoObjectOrientation
1.1.1WhatIsanObject?
1.1.2Inheritance
1.1.3Polymorphism
1.1.4AFewMoreTerms
1.2BasicRubySyntaxandSemantics
1.2.1KeywordsandIdentifiers
1.2.2CommentsandEmbeddedDocumentation
1.2.3Constants,Variables,andTypes
1.2.4OperatorsandPrecedence
1.2.5ASampleProgram
1.2.6LoopingandBranching
1.2.7Exceptions
1.3OOPinRuby
1.3.1Objects

1.3.2Built-inClasses
1.3.3ModulesandMixins
1.3.4CreatingClasses
1.3.5MethodsandAttributes
1.4DynamicAspectsofRuby
1.4.1CodingatRuntime
1.4.2Reflection
1.4.3MissingMethods
1.4.4GarbageCollection
1.5TrainingYourIntuition:ThingstoRemember


1.5.1SyntaxIssues
1.5.2PerspectivesinProgramming
1.5.3Ruby’scaseStatement
1.5.4RubyismsandIdioms
1.5.5ExpressionOrientationandOtherMiscellaneousIssues
1.6RubyJargonandSlang
1.7Conclusion
2WorkingwithStrings
2.1RepresentingOrdinaryStrings
2.2RepresentingStringswithAlternateNotations
2.3UsingHere-Documents
2.4FindingtheLengthofaString
2.5ProcessingaLineataTime
2.6ProcessingaCharacterorByteataTime
2.7PerformingSpecializedStringComparisons
2.8TokenizingaString
2.9FormattingaString
2.10UsingStringsasIOObjects

2.11ControllingUppercaseandLowercase
2.12AccessingandAssigningSubstrings
2.13SubstitutinginStrings
2.14SearchingaString
2.15ConvertingBetweenCharactersandASCIICodes
2.16ImplicitandExplicitConversion
2.17AppendinganItemontoaString
2.18RemovingTrailingNewlinesandOtherCharacters
2.19TrimmingWhitespacefromaString
2.20RepeatingStrings
2.21EmbeddingExpressionswithinStrings
2.22DelayedInterpolationofStrings
2.23ParsingComma-SeparatedData
2.24ConvertingStringstoNumbers(DecimalandOtherwise)


2.25EncodingandDecodingrot13Text
2.26EncryptingStrings
2.27CompressingStrings
2.28CountingCharactersinStrings
2.29ReversingaString
2.30RemovingDuplicateCharacters
2.31RemovingSpecificCharacters
2.32PrintingSpecialCharacters
2.33GeneratingSuccessiveStrings
2.34Calculatinga32-BitCRC
2.35CalculatingtheSHA-256HashofaString
2.36CalculatingtheLevenshteinDistanceBetweenTwoStrings
2.37EncodingandDecodingBase64Strings
2.38ExpandingandCompressingTabCharacters

2.39WrappingLinesofText
2.40Conclusion
3WorkingwithRegularExpressions
3.1RegularExpressionSyntax
3.2CompilingRegularExpressions
3.3EscapingSpecialCharacters
3.4UsingAnchors
3.5UsingQuantifiers
3.6PositiveandNegativeLookahead
3.7PositiveandNegativeLookbehind
3.8AccessingBackreferences
3.9NamedMatches
3.10UsingCharacterClasses
3.11ExtendedRegularExpressions
3.12MatchingaNewlinewithaDot
3.13UsingEmbeddedOptions
3.14UsingEmbeddedSubexpressions
3.14.1RecursioninRegularExpressions


3.15AFewSampleRegularExpressions
3.15.1MatchinganIPAddress
3.15.2MatchingaKeyword-ValuePair
3.15.3MatchingRomanNumerals
3.15.4MatchingNumericConstants
3.15.5MatchingaDate/TimeString
3.15.6DetectingDoubledWordsinText
3.15.7MatchingAll-CapsWords
3.15.8MatchingVersionNumbers
3.15.9AFewOtherPatterns

3.16Conclusion
4InternationalizationinRuby
4.1BackgroundandTerminology
4.2WorkingwithCharacterEncodings
4.2.1Normalization
4.2.2EncodingConversions
4.2.3Transliteration
4.2.4Collation
4.3Translations
4.3.1Defaults
4.3.2Namespaces
4.3.3Interpolation
4.3.4Pluralization
4.4LocalizedFormatting
4.4.1DatesandTimes
4.4.2Numbers
4.4.3Currencies
4.5Conclusion
5PerformingNumericalCalculations
5.1RepresentingNumbersinRuby
5.2BasicOperationsonNumbers
5.3RoundingFloatingPointValues


5.4ComparingFloatingPointNumbers
5.5FormattingNumbersforOutput
5.6FormattingNumberswithCommas
5.7WorkingwithVeryLargeIntegers
5.8UsingBigDecimal
5.9WorkingwithRationalValues

5.10MatrixManipulation
5.11WorkingwithComplexNumbers
5.12Usingmathn
5.13FindingPrimeFactorization,GCD,andLCM
5.14WorkingwithPrimeNumbers
5.15ImplicitandExplicitNumericConversion
5.16CoercingNumericValues
5.17PerformingBit-LevelOperationsonNumbers
5.18PerformingBaseConversions
5.19FindingCubeRoots,FourthRoots,andSoOn
5.20DeterminingtheArchitecture’sByteOrder
5.21NumericalComputationofaDefiniteIntegral
5.22TrigonometryinDegrees,Radians,andGrads
5.23FindingLogarithmswithArbitraryBases
5.24FindingtheMean,Median,andModeofaDataSet
5.25VarianceandStandardDeviation
5.26FindingaCorrelationCoefficient
5.27GeneratingRandomNumbers
5.28CachingFunctionswithMemoization
5.29Conclusion
6SymbolsandRanges
6.1Symbols
6.1.1SymbolsasEnumerations
6.1.2SymbolsasMetavalues
6.1.3Symbols,Variables,andMethods
6.1.4Convertingto/fromSymbols


6.2Ranges
6.2.1OpenandClosedRanges

6.2.2FindingEndpoints
6.2.3IteratingOverRanges
6.2.4TestingRangeMembership
6.2.5ConvertingtoArrays
6.2.6BackwardRanges
6.2.7TheFlip-FlopOperator
6.2.8CustomRanges
6.3Conclusion
7WorkingwithTimesandDates
7.1DeterminingtheCurrentTime
7.2WorkingwithSpecificTimes(Post-Epoch)
7.3DeterminingtheDayoftheWeek
7.4DeterminingtheDateofEaster
7.5FindingtheNthWeekdayinaMonth
7.6ConvertingBetweenSecondsandLargerUnits
7.7ConvertingtoandfromtheEpoch
7.8WorkingwithLeapSeconds:Don’t!
7.9FindingtheDayoftheYear
7.10ValidatingaDateorTime
7.11FindingtheWeekoftheYear
7.12DetectingLeapYears
7.13ObtainingtheTimeZone
7.14WorkingwithHoursandMinutesOnly
7.15ComparingTimeValues
7.16AddingIntervalstoTimeValues
7.17ComputingtheDifferenceinTwoTimeValues
7.18WorkingwithSpecificDates(Pre-Epoch)
7.19Time,Date,andDateTime
7.20ParsingaDateorTimeString
7.21FormattingandPrintingTimeValues



7.22TimeZoneConversions
7.23DeterminingtheNumberofDaysinaMonth
7.24DividingaMonthintoWeeks
7.25Conclusion
8Arrays,Hashes,andOtherEnumerables
8.1WorkingwithArrays
8.1.1CreatingandInitializinganArray
8.1.2AccessingandAssigningArrayElements
8.1.3FindinganArray’sSize
8.1.4ComparingArrays
8.1.5SortinganArray
8.1.6SelectingfromanArraybyCriteria
8.1.7UsingSpecializedIndexingFunctions
8.1.8ImplementingaSparseMatrix
8.1.9UsingArraysasMathematicalSets
8.1.10RandomizinganArray
8.1.11UsingMultidimensionalArrays
8.1.12FindingElementsinOneArrayButNotAnother
8.1.13TransformingorMappingArrays
8.1.14RemovingnilValuesfromanArray
8.1.15RemovingSpecificArrayElements
8.1.16ConcatenatingandAppendingontoArrays
8.1.17UsinganArrayasaStackorQueue
8.1.18IteratingoveranArray
8.1.19InterposingDelimiterstoFormaString
8.1.20ReversinganArray
8.1.21RemovingDuplicateElementsfromanArray
8.1.22InterleavingArrays

8.1.23CountingFrequencyofValuesinanArray
8.1.24InvertinganArraytoFormaHash
8.1.25SynchronizedSortingofMultipleArrays
8.1.26EstablishingaDefaultValueforNewArrayElements


8.2WorkingwithHashes
8.2.1CreatingaNewHash
8.2.2SpecifyingaDefaultValueforaHash
8.2.3AccessingandAddingKey-ValuePairs
8.2.4DeletingKey-ValuePairs
8.2.5IteratingOveraHash
8.2.6InvertingaHash
8.2.7DetectingKeysandValuesinaHash
8.2.8ExtractingHashesintoArrays
8.2.9SelectingKey-ValuePairsbyCriteria
8.2.10SortingaHash
8.2.11MergingTwoHashes
8.2.12CreatingaHashfromanArray
8.2.13FindingDifferenceorIntersectionofHashKeys
8.2.14UsingaHashasaSparseMatrix
8.2.15ImplementingaHashwithDuplicateKeys
8.2.16OtherHashOperations
8.3EnumerablesinGeneral
8.3.1TheinjectMethod
8.3.2UsingQuantifiers
8.3.3ThepartitionMethod
8.3.4IteratingbyGroups
8.3.5ConvertingtoArraysorSets
8.3.6UsingEnumeratorObjects

8.4MoreonEnumerables
8.4.1SearchingandSelecting
8.4.2CountingandComparing
8.4.3Iterating
8.4.4ExtractingandConverting
8.4.5LazyEnumerators
8.5Conclusion
9MoreAdvancedDataStructures


9.1WorkingwithSets
9.1.1SimpleSetOperations
9.1.2MoreAdvancedSetOperations
9.2WorkingwithStacksandQueues
9.2.1ImplementingaStricterStack
9.2.2DetectingUnbalancedPunctuationinExpressions
9.2.3UnderstandingStacksandRecursion
9.2.4ImplementingaStricterQueue
9.3WorkingwithTrees
9.3.1ImplementingaBinaryTree
9.3.2SortingUsingaBinaryTree
9.3.3UsingaBinaryTreeasaLookupTable
9.3.4ConvertingaTreetoaStringorArray
9.4WorkingwithGraphs
9.4.1ImplementingaGraphasanAdjacencyMatrix
9.4.2DeterminingWhetheraGraphIsFullyConnected
9.4.3DeterminingWhetheraGraphHasanEulerCircuit
9.4.4DeterminingWhetheraGraphHasanEulerPath
9.4.5GraphToolsinRuby
9.5Conclusion

10I/OandDataStorage
10.1WorkingwithFilesandDirectories
10.1.1OpeningandClosingFiles
10.1.2UpdatingaFile
10.1.3AppendingtoaFile
10.1.4RandomAccesstoFiles
10.1.5WorkingwithBinaryFiles
10.1.6LockingFiles
10.1.7PerformingSimpleI/O
10.1.8PerformingBufferedandUnbufferedI/O
10.1.9ManipulatingFileOwnershipandPermissions
10.1.10RetrievingandSettingTimestampInformation


10.1.11CheckingFileExistenceandSize
10.1.12CheckingSpecialFileCharacteristics
10.1.13WorkingwithPipes
10.1.14PerformingSpecialI/OOperations
10.1.15UsingNonblockingI/O
10.1.16Usingreadpartial
10.1.17ManipulatingPathnames
10.1.18UsingthePathnameClass
10.1.19Command-LevelFileManipulation
10.1.20GrabbingCharactersfromtheKeyboard
10.1.21ReadinganEntireFileintoMemory
10.1.22IteratingOveraFilebyLines
10.1.23IteratingOveraFilebyByteorCharacter
10.1.24TreatingaStringAsaFile
10.1.25CopyingaStream
10.1.26WorkingwithCharacterEncodings

10.1.27ReadingDataEmbeddedinaProgram
10.1.28ReadingProgramSource
10.1.29WorkingwithTemporaryFiles
10.1.30ChangingandSettingtheCurrentDirectory
10.1.31ChangingtheCurrentRoot
10.1.32IteratingOverDirectoryEntries
10.1.33GettingaListofDirectoryEntries
10.1.34CreatingaChainofDirectories
10.1.35DeletingaDirectoryRecursively
10.1.36FindingFilesandDirectories
10.2Higher-LevelDataAccess
10.2.1SimpleMarshaling
10.2.2“DeepCopying”withMarshal
10.2.3MoreComplexMarshaling
10.2.4MarshalingwithYAML
10.2.5PersistingDatawithJSON


10.2.6WorkingwithCSVData
10.2.7SQLite3forSQLDataStorage
10.3ConnectingtoExternalDataStores
10.3.1ConnectingtoMySQLDatabases
10.3.2ConnectingtoPostgreSQLDatabases
10.3.3Object-RelationalMappers(ORMs)
10.3.4ConnectingtoRedisDataStores
10.4Conclusion
11OOPandDynamicFeaturesinRuby
11.1EverydayOOPTasks
11.1.1UsingMultipleConstructors
11.1.2CreatingInstanceAttributes

11.1.3UsingMoreElaborateConstructors
11.1.4CreatingClass-LevelAttributesandMethods
11.1.5InheritingfromaSuperclass
11.1.6TestingClassesofObjects
11.1.7TestingEqualityofObjects
11.1.8ControllingAccesstoMethods
11.1.9CopyinganObject
11.1.10Usinginitialize_copy
11.1.11Understandingallocate
11.1.12WorkingwithModules
11.1.13TransformingorConvertingObjects
11.1.14CreatingData-OnlyClasses(Structs)
11.1.15FreezingObjects
11.1.16UsingtapinMethodChaining
11.2MoreAdvancedTechniques
11.2.1SendinganExplicitMessagetoanObject
11.2.2SpecializinganIndividualObject
11.2.3NestingClassesandModules
11.2.4CreatingParametricClasses
11.2.5StoringCodeasProcObjects


11.2.6StoringCodeasMethodObjects
11.2.7UsingSymbolsasBlocks
11.2.8HowModuleInclusionWorks
11.2.9DetectingDefaultParameters
11.2.10DelegatingorForwarding
11.2.11DefiningClass-LevelReadersandWriters
11.2.12WorkinginAdvancedProgrammingDisciplines
11.3WorkingwithDynamicFeatures

11.3.1EvaluatingCodeDynamically
11.3.2RetrievingaConstantbyName
11.3.3RetrievingaClassbyName
11.3.4Usingdefine_method
11.3.5ObtainingListsofDefinedEntities
11.3.6RemovingDefinitions
11.3.7HandlingReferencestoNonexistentConstants
11.3.8HandlingCallstoNonexistentMethods
11.3.9ImprovedSecuritywithtaint
11.3.10DefiningFinalizersforObjects
11.4ProgramIntrospection
11.4.1TraversingtheObjectSpace
11.4.2ExaminingtheCallStack
11.4.3TrackingChangestoaClassorObjectDefinition
11.4.4MonitoringProgramExecution
11.5Conclusion
12GraphicalInterfacesforRuby
12.1Shoes4
12.1.1StartingOutwithShoes
12.1.2AnInteractiveButton
12.1.3TextandInput
12.1.4Layout
12.1.5ImagesandShapes
12.1.6Events


12.1.7OtherNotes
12.2Ruby/Tk
12.2.1Overview
12.2.2ASimpleWindowedApplication

12.2.3WorkingwithButtons
12.2.4WorkingwithTextFields
12.2.5WorkingwithOtherWidgets
12.2.6OtherNotes
12.3Ruby/GTK3
12.3.1Overview
12.3.2ASimpleWindowedApplication
12.3.3WorkingwithButtons
12.3.4WorkingwithTextFields
12.3.5WorkingwithOtherWidgets
12.3.6OtherNotes
12.4QtRuby
12.4.1Overview
12.4.2ASimpleWindowedApplication
12.4.3WorkingwithButtons
12.4.4WorkingwithTextFields
12.4.5WorkingwithOtherWidgets
12.4.6OtherNotes
12.5Swing
12.6OtherGUIToolkits
12.6.1UNIXandX11
12.6.2FXRuby(FOX)
12.6.3RubyMotionforiOSandMacOSX
12.6.4TheWindowsWin32API
12.7Conclusion
13ThreadsandConcurrency
13.1CreatingandManipulatingThreads
13.1.1CreatingThreads



13.1.2AccessingThread-LocalVariables
13.1.3QueryingandChangingThreadStatus
13.1.4AchievingaRendezvous(andCapturingaReturnValue)
13.1.5DealingwithExceptions
13.1.6UsingaThreadGroup
13.2SynchronizingThreads
13.2.1PerformingSimpleSynchronization
13.2.2SynchronizingAccesswithaMutex
13.2.3UsingtheBuilt-inQueueClasses
13.2.4UsingConditionVariables
13.2.5OtherSynchronizationTechniques
13.2.6SettingaTimeoutforanOperation
13.2.7WaitingforanEvent
13.2.8CollectionSearchinginParallel
13.2.9RecursiveDeletioninParallel
13.3FibersandCooperativeMultitasking
13.4Conclusion
14ScriptingandSystemAdministration
14.1RunningExternalPrograms
14.1.1Usingsystemandexec
14.1.2CapturingCommandOutput
14.1.3ManipulatingProcesses
14.1.4ManipulatingStandardInputandOutput
14.2Command-LineOptionsandArguments
14.2.1WorkingwithARGV
14.2.2WorkingwithARGF
14.2.3ParsingCommand-LineOptions
14.3TheShellLibrary
14.3.1UsingShellforI/ORedirection
14.3.2OtherNotesonShell

14.4AccessingEnvironmentVariables
14.4.1GettingandSettingEnvironmentVariables


14.4.2StoringEnvironmentVariablesasanArrayorHash
14.5WorkingwithFiles,Directories,andTrees
14.5.1AFewWordsonTextFilters
14.5.2CopyingaDirectoryTree
14.5.3DeletingFilesbyAgeorOtherCriteria
14.5.4DeterminingFreeSpaceonaDisk
14.6OtherScriptingTasks
14.6.1DistributingRubyPrograms
14.6.2PipingintotheRubyInterpreter
14.6.3TestingWhetheraProgramIsRunningInteractively
14.6.4DeterminingtheCurrentPlatformorOperatingSystem
14.6.5UsingtheEtcModule
14.7Conclusion
15RubyandDataFormats
15.1ParsingJSON
15.1.1NavigatingJSONData
15.1.2HandlingNon-JSONDataTypes
15.1.3OtherJSONLibraries
15.2ParsingXML(andHTML)
15.2.1DocumentParsing
15.2.2StreamParsing
15.3WorkingwithRSSandAtom
15.3.1ParsingFeeds
15.3.2GeneratingFeeds
15.4ManipulatingImageDatawithRMagick
15.4.1CommonGraphicsTasks

15.4.2SpecialEffectsandTransformations
15.4.3TheDrawingAPI
15.5CreatingPDFDocumentswithPrawn
15.5.1BasicConceptsandTechniques
15.5.2AnExampleDocument
15.6Conclusion


16TestingandDebugging
16.1TestingwithRSpec
16.2TestingwithMinitest
16.3TestingwithCucumber
16.4UsingthebyebugDebugger
16.5UsingpryforDebugging
16.6MeasuringPerformance
16.7Pretty-PrintingObjects
16.8NotCoveredHere
16.9Conclusion
17PackagingandDistributingCode
17.1LibrariesandRubygems
17.1.1UsingRubygems
17.1.2CreatingGems
17.2ManagingDependencieswithBundler
17.2.1SemanticVersioning
17.2.2DependenciesfromGit
17.2.3CreatingGemswithBundler
17.2.4PrivateGems
17.3UsingRDoc
17.3.1SimpleMarkup
17.3.2AdvancedDocumentationwithYard

17.4Conclusion
18NetworkProgramming
18.1NetworkServers
18.1.1ASimpleServer:TimeofDay
18.1.2ImplementingaThreadedServer
18.1.3CaseStudy:APeer-to-PeerChessServer
18.2NetworkClients
18.2.1RetrievingTrulyRandomNumbersfromtheWeb
18.2.2ContactinganOfficialTimeserver
18.2.3InteractingwithaPOPServer


18.2.4SendingMailwithSMTP
18.2.5InteractingwithanIMAPServer
18.2.6Encoding/DecodingAttachments
18.2.7CaseStudy:AMail-NewsGateway
18.2.8RetrievingaWebPagefromaURL
18.2.9UsingtheOpen-URILibrary
18.3Conclusion
19RubyandWebApplications
19.1HTTPServers
19.1.1ASimpleHTTPServer
19.1.2RackandWebServers
19.2ApplicationFrameworks
19.2.1RoutinginSinatra
19.2.2RoutinginRails
19.2.3ParametersinSinatra
19.2.4ParametersinRails
19.3StoringData
19.3.1Databases

19.3.2DataStores
19.4GeneratingHTML
19.4.1ERB
19.4.2Haml
19.4.3OtherTemplatingSystems
19.5TheAssetPipeline
19.5.1CSSandSass
19.5.2JavaScriptandCoffeeScript
19.6WebServicesviaHTTP
19.6.1JSONforAPIs
19.6.2REST(andREST-ish)APIs
19.7GeneratingStaticSites
19.7.1Middleman
19.7.2OtherStaticSiteGenerators


×