Beginning ruby From Novice to Professional — Third Edition — Peter Cooper Beginning Ruby From Novice to Professional Third Edition Peter Cooper Beginning Ruby: From Novice to Professional, Third Edition Peter Cooper Louth, Lincs United Kingdom ISBN-13 (pbk): 978-1-4842-1279-0 ISBN-13 (electronic): 978-1-4842-1278-3 DOI 10.1007/978-1-4842-1278-3 Library of Congress Control Number: 2016945758 Copyright © 2016 by Peter Cooper This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director: Welmoed Spahr Lead Editor: Steve Anglin Technical Reviewer: Ronald Petty Editorial Board: Steve Anglin, Pramila Balan, Aaron Black, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, James Markham, Natalie Pao, Susan McDermott, Matthew Moodie, Ben Renow-Clarke, Gwenan Spearing Coordinating Editor: Mark Powers Copy Editor: Kezia Endsley Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected] , or visit w ww.springeronline.com . Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail [email protected] , or visit w ww.apress.com . Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at w ww.apress.com/bulk-sales . Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com/9781484212790 . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter. Printed on acid-free paper For Laura, Penny and Imogen Contents at a Glance Foreword ..............................................................................................................xxiii About the Author .................................................................................................xxvii About the Technical Reviewer ..............................................................................xxix Acknowledgments ................................................................................................xxxi Introduction ........................................................................................................xxxiii ■ Part 1: Foundations and Scaffolding ..................................................1 ■ Chapter 1: Let’s Get It Started: Installing Ruby .....................................................3 ■ Chapter 2: Programming == Joy: A Whistle-Stop Tour of Ruby and Object Orientation ...........................................................................................................11 ■ Chapter 3: Ruby’s Building Blocks: Data, Expressions, and Flow Control ...........29 ■ Chapter 4: Developing Your First Ruby Application .............................................73 ■ Chapter 5: The Ruby Ecosystem ..........................................................................93 ■ Part 2: The Core of Ruby .................................................................105 ■ Chapter 6: Classes, Objects, and Modules .........................................................107 ■ Chapter 7: Projects and Libraries ......................................................................149 ■ Chapter 8: Documentation, Error Handling, Debugging, and Testing .................163 ■ Chapter 9: Files and Databases .........................................................................187 ■ Chapter 10: Distributing Ruby Code and Libraries ............................................225 ■ Chapter 11: Advanced Ruby Features................................................................243 ■ Chapter 12: Tying It Together: Developing a Larger Ruby Application ..............269 v ■ CONTENTS AT A GLANCE ■ Part 3: Ruby Online .........................................................................303 ■ Chapter 13: Two Web Application Approaches: Rails and Sinatra .....................305 ■ Chapter 14: Ruby and the Internet ....................................................................343 ■ Chapter 15: Networking and Sockets ................................................................363 ■ Chapter 16: Useful Ruby Libraries .....................................................................379 ■ Appendix A: Ruby Primer and Review for Developers .......................................417 ■ Appendix B: Useful Resources ...........................................................................443 Index .....................................................................................................................449 vi Contents Foreword ..............................................................................................................xxiii About the Author .................................................................................................xxvii About the Technical Reviewer ..............................................................................xxix Acknowledgments ................................................................................................xxxi Introduction ........................................................................................................xxxiii ■ Part 1: Foundations and Scaffolding ..................................................1 ■ Chapter 1: Let’s Get It Started: Installing Ruby .....................................................3 Installing Ruby ..................................................................................................................4 Windows .................................................................................................................................................4 Mac OS X / macOS .................................................................................................................................6 Linux .......................................................................................................................................................7 Other Platforms ......................................................................................................................................9 Summary ........................................................................................................................10 ■ Chapter 2: Programming == Joy: A Whistle-Stop Tour of Ruby and Object Orientation ...........................................................................................................11 Baby Steps .....................................................................................................................11 irb: Interactive Ruby ..............................................................................................................................12 Ruby Is “English for Computers” ..........................................................................................................12 Why Ruby Makes a Great Programming Language ..............................................................................13 Trails for the Mind .................................................................................................................................14 Turning Ideas into Ruby Code .........................................................................................15 How Ruby Understands Concepts with Objects and Classes ...............................................................15 The Making of a Person ........................................................................................................................16 vii ■ CONTENTS Basic Variables .....................................................................................................................................17 From People to Pets .............................................................................................................................18 Everything Is an Object ..................................................................................................21 Kernel Methods ....................................................................................................................................22 Passing Data to Methods ......................................................................................................................23 Using the Methods of the String Class .................................................................................................24 Using Ruby in a Non–Object-Oriented Style ...................................................................25 Summary ........................................................................................................................26 ■ Chapter 3: Ruby’s Building Blocks: Data, Expressions, and Flow Control ...........29 Numbers and Expressions ..............................................................................................29 Basic Expressions .................................................................................................................................29 Variables ...............................................................................................................................................30 Comparison Operators and Expressions ...............................................................................................31 Looping Through Numbers with Blocks and Iterators ..........................................................................33 Floating Point Numbers ........................................................................................................................35 Constants ..............................................................................................................................................36 Text and Strings .............................................................................................................36 String Literals .......................................................................................................................................36 String Expressions ................................................................................................................................37 Interpolation .........................................................................................................................................39 String Methods .....................................................................................................................................40 Regular Expressions and String Manipulation ......................................................................................41 Arrays and Lists ..............................................................................................................47 Basic Arrays ..........................................................................................................................................47 Splitting Strings into Arrays ..................................................................................................................49 Array Iteration .......................................................................................................................................50 Other Array Methods .............................................................................................................................51 Hashes............................................................................................................................53 Basic Hash Methods .............................................................................................................................53 Hashes Within Hashes ..........................................................................................................................55 viii ■ CONTENTS Flow Control ...................................................................................................................56 if and unless .........................................................................................................................................56 ?, the Ternary Operator .........................................................................................................................57 elsif and case .......................................................................................................................................58 while and until ......................................................................................................................................60 Code Blocks ..........................................................................................................................................61 Other Useful Building Blocks ..........................................................................................62 Dates and Times ...................................................................................................................................62 Large Numbers .....................................................................................................................................65 Ranges ..................................................................................................................................................66 Symbols ................................................................................................................................................68 Converting Objects to Other Classes ....................................................................................................69 Summary ........................................................................................................................70 ■ Chapter 4: Developing Your First Ruby Application .............................................73 Working with Source Code Files.....................................................................................73 Creating a Test File ...............................................................................................................................73 A Simple Source Code File ...................................................................................................................75 Running Your Source Code ...................................................................................................................75 Our Application: A Text Analyzer .....................................................................................77 Required Basic Features .......................................................................................................................77 Building the Basic Application ..............................................................................................................78 Obtaining Some Dummy Text ................................................................................................................78 Loading Text Files and Counting Lines .................................................................................................79 Counting Characters .............................................................................................................................80 Counting Words ....................................................................................................................................81 Counting Sentences and Paragraphs ...................................................................................................82 Calculating Averages ............................................................................................................................83 The Source Code So Far .......................................................................................................................84 ix