Digital Library

The Well-Grounded Rubyist (David A. Black, Joseph Leo III)(Z-Library)

,

Share E-Book

The Well-Grounded Rubyist (David A. Black, Joseph Leo III)(Z-Library)

Author

,

Rating 4.5 AI initial rating

Log in to rate

Programming Language
Language English

The Well-Grounded Rubyist, Third Edition is a beautifully written tutorial that begins with your first Ruby program and takes you all the way to sophisticated topics like reflection, threading, and recursion. Ruby masters David A. Black and Joe Leo distill their years of knowledge for you, concentrating on the language and its uses so you can use Ruby in any way you choose. Updated for Ruby 2.5. About the Technology Designed for developer productivity, Ruby is an easy-to-learn dynamic language perfect for creating virtually any kind of software. Its famously friendly development community, countless libraries, and amazing tools, like the Rails framework, have established it as the language of choice for high-profile companies, including GitHub, SlideShare, and Shopify. The future is bright for the well-grounded Rubyist! About the Book In The Well-Grounded Rubyist, Third Edition, expert authors David A. Black and Joseph Leo III deliver Ruby mastery in an easy-to-read, casual style. You'll lock in core principles as you write your first Ruby programs. Then, you'll progressively build up to topics like reflection, threading, and recursion, cementing your knowledge with high-value exercises to practice your skills along the way. What's Inside • Basic Ruby syntax • Running Ruby extensions • FP concepts like currying, side-effect-free code, and recursion • Ruby 2.5 updates About the Reader For readers with beginner-level programming skills, as well as more advanced programmers interested in Ruby and experienced Rubyists looking to review the foundations of their practice.

Format PDF
Size 4.5 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
M A N N I N G David A. Black Joseph Leo III THIRD EDITION
Page 2
Praise for the Second Edition Once again, David Black has written the definitive book on Ruby. A must have for any Rubyist! —William Wheeler TEKsystems The Well-Grounded Rubyist digs into Ruby’s quirks and provides powerful insights into how the core artifacts interact. Revelatory. —Ted Roche Ted Roche & Associates, LLC All wheat, no chaff—takes you from Ruby programmer to full-fledged Rubyist. —Doug Sparling Andrews McMeel Universal The best way to learn Ruby fundamentals. —Derek Sivers sivers.org If you have ever read a tutorial on Ruby on Rails and wondered, ‘Okay, it works, but why and how?’ then this book is for you. A great book to learn Ruby from the beginning. —Andrea Tarocchi Istituto Clinico Città Studi (ICCS) Any passionate Rubyist can discover plenty of practical treasures inside. —Marius Butuc Influitive
Page 3
(This page has no text content)
Page 4
The Well-Grounded Rubyist THIRD EDITION DAVID A. BLACK JOSEPH LEO III M A N N I N G SHELTER ISLAND
Page 5
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com © 2019 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Jenny Stout 20 Baldwin Road Technical development editor: Arthur Zubarev PO Box 761 Review editor: Ivan Martinović Shelter Island, NY 11964 Production editor: Céline Durassier Copyeditor: Andy Carroll Proofreader: Katie Tennant Technical proofreader: René van den Berg Typesetter: Dottie Marsico Cover designer: Marija Tudor ISBN 9781617295218 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – SP – 24 23 22 21 20 19
Page 6
For David. —David For Diana, for teaching me how to take it easy. I am still a work in progress. —Joseph
Page 7
(This page has no text content)
Page 8
brief contents PART 1 RUBY FOUNDATIONS......................................................... 1 1 ■ Bootstrapping your Ruby literacy 3 2 ■ Objects, methods, and local variables 35 3 ■ Organizing objects with classes 64 4 ■ Modules and program organization 95 5 ■ The default object (self), scope, and visibility 125 6 ■ Control-flow techniques 159 PART 2 BUILT-IN CLASSES AND MODULES................................... 201 7 ■ Built-in essentials 203 8 ■ Strings, symbols, and other scalar objects 233 9 ■ Collection and container objects 268 10 ■ Collections central: Enumerable and Enumerator 303 11 ■ Regular expressions and regexp-based string operations 351 12 ■ File and I/O operations 385 PART 3 RUBY DYNAMICS ........................................................... 413 13 ■ Object individuation 415 14 ■ Callable and runnable objects 445 15 ■ Callbacks, hooks, and runtime introspection 485 16 ■ Ruby and functional programming 515vii
Page 9
(This page has no text content)
Page 10
contents preface xix acknowledgments xx about this book xxii about the authors xxvii about the cover illustration xxviii PART 1 RUBY FOUNDATIONS..........................................1 1 Bootstrapping your Ruby literacy 3 1.1 Basic Ruby language literacy 4 Installing Ruby and using a text editor 4 ■ A Ruby syntax survival kit 6 ■ The variety of Ruby identifiers 7 ■ Method calls, messages, and Ruby objects 9 ■ Writing and saving a simple program 11 ■ Feeding the program to Ruby 12 Keyboard and file I/O 14 1.2 Anatomy of the Ruby installation 17 The Ruby standard library subdirectory (RbConfig::CONFIG [“rubylibdir”]) 18 ■ The C extensions directory (RbConfig::CONFIG [“archdir”]) 18 ■ The site_ruby (RbConfig::CONFIG[“sitedir”]) and vendor_ruby (RbConfig::CONFIG[“vendordir”]) directories 19 Standard Ruby gems and the gems directory 19 1.3 Ruby extensions and programming libraries 20 Loading external files and extensions 21 ■ “Load”-ing a file ix
Page 11
CONTENTSxin the default load path 22 ■ “Require”-ing a feature 23 require_relative 24 1.4 Out-of-the-box Ruby tools and applications 25 Interpreter command-line switches 25 ■ A closer look at interactive Ruby interpretation with irb 29 ■ The rake task- management utility 31 ■ Installing packages with the gem command 33 2 Objects, methods, and local variables 35 2.1 Talking to objects 36 Ruby and object orientation 36 ■ Creating a generic object 37 ■ Methods that take arguments 39 The return value of a method 40 2.2 Crafting an object: the behavior of a ticket 41 The ticket object, behavior first 41 ■ Querying the ticket object 42 ■ Shortening the ticket code via string interpolation 43 ■ Ticket availability: expressing Boolean state in a method 44 2.3 The innate behaviors of an object 46 Identifying objects uniquely with the object_id method 47 Querying an object’s abilities with the respond_to? method 48 Sending messages to objects with the send method 48 2.4 A close look at method arguments 50 Required and optional arguments 50 ■ Default values for arguments 51 ■ Order of parameters and arguments 52 What you can’t do in argument lists 54 2.5 Local variables and variable assignment 56 Variables, objects, and references 57 ■ References in variable assignment and reassignment 59 ■ References and method arguments 60 ■ Local variables and the things that look like them 62 3 Organizing objects with classes 64 3.1 Classes and instances 65 Instance methods 66 ■ Overriding methods 67 Reopening classes 67 3.2 Instance variables and object state 69 Initializing an object with state 71 3.3 Setter methods 72 The equal sign (=) in method names 73 ■ Syntactic sugar for assignment-like methods 74 ■ Setter methods unleashed 75
Page 12
CONTENTS xi3.4 Attributes and the attr_* method family 77 Automating the creation of attributes 78 ■ Summary of attr_* methods 80 3.5 Inheritance and the Ruby class hierarchy 80 Single inheritance: one to a customer 81 ■ Object ancestry and the not-so-missing link: the Object class 82 ■ BasicObject 83 3.6 Classes as objects and message receivers 83 Creating class objects 83 ■ How class objects call methods 85 A singleton method by any other name ... 86 ■ When, and why, to write a class method 87 ■ Class methods vs. instance methods 88 3.7 Constants up close 89 Basic use of constants 90 ■ Reassigning vs. modifying constants 91 3.8 Nature vs. nurture in Ruby objects 92 4 Modules and program organization 95 4.1 Basics of module creation and use 96 A module encapsulating “stacklikeness” 97 ■ Mixing a module into a class 99 ■ Using the module further 101 4.2 Modules, classes, and method lookup 103 Illustrating the basics of method lookup 103 ■ Defining the same method more than once 106 ■ How prepend works 109 How extend works 110 ■ The rules of method lookup summarized 111 ■ Going up the method search path with super 112 ■ Inspecting method hierarchies with method and super_method 114 4.3 The method_missing method 115 Combining method_missing and super 116 4.4 Class/module design and naming 121 Mix-ins and/or inheritance 121 ■ Nesting modules and classes 123 5 The default object (self), scope, and visibility 125 5.1 Understanding self, the current/default object 126 Who gets to be self, and where 126 ■ The top-level self object 128 Self inside class, module, and method definitions 129 ■ Self as the default receiver of messages 132 ■ Resolving instance variables through self 134
Page 13
CONTENTSxii5.2 Determining scope 136 Global scope and global variables 136 ■ Local scope 139 The interaction between local scope and self 141 ■ Scope and resolution of constants 143 ■ Class variable syntax, scope, and visibility 145 5.3 Deploying method-access rules 151 Private methods 151 ■ Protected methods 155 5.4 Writing and using top-level methods 156 Defining a top-level method 156 ■ Predefined (built-in) top-level methods 157 6 Control-flow techniques 159 6.1 Conditional code execution 160 The if keyword and its variants 160 ■ Assignment syntax in condition bodies and tests 165 ■ case statements 167 6.2 Repeating actions with loops 172 Unconditional looping with the loop method 173 ■ Conditional looping with the while and until keywords 174 ■ Multiple assignment in conditional statements 176 ■ Looping based on a list of values 176 6.3 Iterators and code blocks 177 The ingredients of iteration 177 ■ Iteration, home-style 178 The anatomy of a method call 179 ■ Curly braces vs. do/end in code block syntax 179 ■ Implementing times 181 The importance of being each 182 ■ From each to map 184 Block parameters and variable scope 185 6.4 Error handling and exceptions 189 Raising and rescuing exceptions 189 ■ The rescue keyword to the rescue! 190 ■ Debugging with binding.irb 192 Avoiding NoMethodError with the safe navigation operator 194 Raising exceptions explicitly 195 ■ Capturing an exception in a rescue clause 196 ■ The ensure clause 198 ■ Creating your own exception classes 198 PART 2 BUILT-IN CLASSES AND MODULES....................201 7 Built-in essentials 203 7.1 Ruby’s literal constructors 205 7.2 Recurrent syntactic sugar 206 Defining operators by defining methods 207 ■ Customizing unary operators 209
Page 14
CONTENTS xiii7.3 Bang (!) methods and “danger” 210 Destructive (receiver-changing) effects as danger 210 Destructiveness and “danger” vary independently 212 7.4 Built-in and custom to_* (conversion) methods 213 String conversion: to_s and other methods defined on Object 213 ■ Array conversion with to_a and the * operator 216 ■ Numerical conversion with to_i and to_f 217 ■ Role-playing to_* methods 219 7.5 Boolean states, Boolean objects, and nil 220 True and false as states 221 ■ true and false as objects 223 The special object nil 224 7.6 Comparing two objects 225 Equality tests 226 ■ Comparisons and the Comparable module 227 7.7 Inspecting object capabilities 229 Listing an object’s methods 229 ■ Querying class and module objects 231 ■ Filtered and selected method lists 231 8 Strings, symbols, and other scalar objects 233 8.1 Working with strings 234 String notation 234 ■ Basic string manipulation 239 Querying strings 243 ■ String comparison and ordering 245 ■ String transformation 246 ■ String conversions 249 ■ String encoding: a brief introduction 250 8.2 Symbols and their uses 252 Chief characteristics of symbols 253 ■ Symbols and identifiers 254 ■ Symbols in practice 255 ■ Strings and symbols in comparison 257 8.3 Numerical objects 258 Numerical classes 259 ■ Performing arithmetic operations 259 8.4 Times and dates 260 Instantiating date/time objects 261 ■ Date/time query methods 263 ■ Date/time formatting methods 264 Date/time conversion methods 265 9 Collection and container objects 268 9.1 Arrays and hashes in comparison 269 9.2 Collection handling with arrays 270 Creating a new array 271 ■ Inserting, retrieving, and removing array elements 275 ■ Combining arrays with
Page 15
CONTENTSxivother arrays 279 ■ Array transformations 280 Array querying 281 9.3 Hashes 282 Creating a new hash 283 ■ Inserting, retrieving, and removing hash pairs 284 ■ Specifying default hash values and behavior 286 ■ Combining hashes with other hashes 287 ■ Hash transformations 288 ■ Hash querying 290 ■ Hashes as final method arguments 291 A detour back to argument syntax: named (keyword) arguments 292 9.4 Ranges 294 Creating a range 294 ■ Range-inclusion logic 295 9.5 Sets 297 Set creation 298 ■ Manipulating set elements 298 Subsets and supersets 301 10 Collections central: Enumerable and Enumerator 303 10.1 Gaining enumerability through each 305 10.2 Enumerable Boolean queries 307 10.3 Enumerable searching and selecting 309 Getting the first match with find 309 ■ Getting all matches with find_all (a.k.a. select) and reject 311 ■ Selecting on threequal matches with grep 311 ■ Organizing selection results with group_by and partition 312 10.4 Element-wise enumerable operations 314 The first method 314 ■ The take and drop methods 316 The min and max methods 316 10.5 Relatives of each 318 reverse_each 318 ■ The each_with_index method (and each.with_index) 318 ■ The each_slice and each_cons methods 319 ■ The slice_ family of methods 320 The cycle method 321 ■ Enumerable reduction with inject 322 10.6 The map method 324 The return value of map 324 ■ In-place mapping with map! 325 10.7 Strings as quasi-enumerables 326 10.8 Sorting enumerables 328 Defining sort-order logic with a block 330 ■ Concise sorting with sort_by 330 ■ Sorting enumerables and the Comparable module 331
Page 16
CONTENTS xv10.9 Enumerators and the next dimension of enumerability 332 Creating enumerators with a code block 333 ■ Attaching enumerators to other objects 335 ■ Implicit creation of enumerators by blockless iterator calls 336 10.10 Enumerator semantics and uses 337 How to use an enumerator’s each method 337 ■ Protecting objects with enumerators 339 ■ Fine-grained iteration with enumerators 341 ■ Adding enumerability with an enumerator 341 10.11 Enumerator method chaining 343 Economizing on intermediate objects 343 ■ Indexing enumerables with with_index 345 ■ Exclusive-or operations on strings with enumerators 345 10.12 Lazy enumerators 347 FizzBuzz with a lazy enumerator 348 11 Regular expressions and regexp-based string operations 351 11.1 What are regular expressions? 352 11.2 Writing regular expressions 352 Seeing patterns 353 ■ Simple matching with literal regular expressions 353 11.3 Building a pattern in a regular expression 355 Literal characters in patterns 356 ■ The dot wildcard character (.) 356 ■ Character classes 357 11.4 Matching, substring captures, and MatchData 358 Capturing submatches with parentheses 358 ■ Match success and failure 360 ■ Two ways of getting the captures 361 Other MatchData information 364 11.5 Fine-tuning regular expressions with quantifiers, anchors, and modifiers 365 Constraining matches with quantifiers 365 ■ Greedy (and non-greedy) quantifiers 367 ■ Regular expression anchors and assertions 369 ■ Modifiers 373 11.6 Converting strings and regular expressions to each other 374 String-to-regexp idioms 375 ■ Going from a regular expression to a string 377
Page 17
CONTENTSxvi11.7 Common methods that use regular expressions 377 String#scan 377 ■ String#split 379 ■ sub/sub! and gsub/gsub! 380 ■ Case equality and grep 382 12 File and I/O operations 385 12.1 How Ruby’s I/O system is put together 386 The IO class 386 ■ IO objects as enumerables 387 STDIN, STDOUT, STDERR 388 ■ A little more about keyboard input 389 12.2 Basic file operations 390 The basics of reading from files 390 ■ Line-based file reading 391 ■ Byte- and character-based file reading 392 Seeking and querying file position 392 ■ Reading files with File class methods 393 ■ Writing to files 394 ■ Using blocks to scope file operations 395 ■ File enumerability 396 File I/O exceptions and errors 397 12.3 Querying IO and File objects 399 Getting information from the File class and the FileTest module 399 Deriving file information with File::Stat 401 12.4 Directory manipulation with the Dir class 401 Reading a directory’s entries 402 ■ Directory manipulation and querying 404 12.5 File tools from the standard library 405 The FileUtils module 406 ■ The Pathname class 408 The StringIO class 409 ■ The open-uri library 411 PART 3 RUBY DYNAMICS ............................................413 13 Object individuation 415 13.1 Where the singleton methods are: the singleton class 416 Dual determination through singleton classes 417 ■ Examining and modifying a singleton class directly 418 ■ Singleton classes on the method-lookup path 420 ■ The singleton_class method 425 Class methods in (even more) depth 425 13.2 Modifying Ruby’s core classes and modules 427 The risks of changing core functionality 427 ■ Additive changes 432 ■ Pass-through overrides 433 ■ Per-object changes with extend 435 ■ Using refinements to affect core behavior 438
Page 18
CONTENTS xvii13.3 BasicObject as ancestor and class 439 Using BasicObject 439 ■ Implementing a subclass of BasicObject 441 14 Callable and runnable objects 445 14.1 Basic anonymous functions: the Proc class 446 Proc objects 446 ■ Procs and blocks and how they differ 447 Block-proc conversions 448 ■ Using Symbol#to_proc for conciseness 452 ■ Procs as closures 453 ■ Proc parameters and arguments 456 14.2 Creating functions with lambda and -> 456 14.3 Methods as objects 458 Capturing Method objects 458 ■ The rationale for methods as objects 459 14.4 The eval family of methods 461 Executing arbitrary strings as code with eval 461 ■ The dangers of eval 462 ■ The instance_eval method 463 Using class_eval (a.k.a. module_eval) 465 14.5 Concurrent execution with threads 467 Killing, stopping, and starting threads 469 ■ A threaded date server 471 ■ Writing a chat server using sockets and threads 472 ■ Threads and variables 474 ■ Manipulating thread keys 475 14.6 Issuing system commands from inside Ruby programs 478 The system and exec methods and backticks 479 Communicating with programs via open and popen3 481 15 Callbacks, hooks, and runtime introspection 485 15.1 Callbacks and hooks 486 Intercepting unrecognized messages with method_missing 486 Trapping include and prepend operations 489 ■ Intercepting extend 490 ■ Intercepting inheritance with Class#inherited 492 The Module#const_missing method 493 ■ The method_added and singleton_method_added methods 494 15.2 Interpreting object capability queries 496 Listing an object’s non-private methods 496 ■ Listing private and protected methods 498 ■ Getting class and module instance methods 499 ■ Listing objects’ singleton methods 501
Page 19
CONTENTSxviii15.3 Introspection of variables and constants 503 Listing local and global variables 503 ■ Listing instance variables 504 15.4 Tracing execution 505 Examining the stack trace with caller 505 ■ Writing a tool for parsing stack traces 506 15.5 Callbacks and method inspection in practice 509 MicroTest background: MiniTest 509 ■ Specifying and implementing MicroTest 511 16 Ruby and functional programming 515 16.1 Understanding pure functions 516 Methods with side effects 517 ■ Pure functions and referential transparency in Ruby 518 ■ Side effects in Ruby’s built-in methods 519 ■ Modifying an object’s state 521 16.2 Immutability 523 Object#freeze and Object#frozen? 524 ■ Frozen string literals 525 16.3 Higher-order functions 526 Method chaining 527 ■ Kernel#itself and Kernel#yield_self 527 Functions that return functions 529 ■ Currying and partial function application 529 16.4 Recursion 533 Lazy evaluation 534 ■ Tail-call optimization 536 index 539
Page 20
preface In the nearly 10 years since the first edition of The Well-Grounded Rubyist was published, Ruby has achieved wild popularity and made an indelible mark on the programming landscape. Once-fledgling startups that used Ruby have become dominant forces in business and technology. Trade schools and teaching programs have sprung up to teach Ruby to newcomers from all walks of life. The programming language with a friendly creator and a warm, inviting community has touched many, many program- mers and changed their professional lives for the better. Ruby is ever changing and evolving. Not only new methods but new programming techniques have become available. Some long-existing techniques have either gained in popularity or fallen out of popular use. The Well-Grounded Rubyist attempts to put its finger on the pulse of the Ruby programming community to teach not only the most important principles but also those most commonly in use today. This edition targets Ruby 2.5. The Well-Grounded Rubyist has become one of the most popular and trusted texts for learning Ruby. Much of the teaching in the book is done by example, giving countless opportunities to follow along with your own code and build on the foundations pro- vided in the text. Earlier editions established this approach, and this third edition expands on it, providing more sample code and exercises than ever before. We’re excited for you to begin your journey through this edition of The Well- Grounded Rubyist. Whether you’re reading this book for the first, second, or third time, we hope you’ll find something new and inspiring, and something that ignites your love of Ruby and keeps it burning! xix
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List