100% found this document useful (1 vote)
16 views

PDF Programming Ruby 1 9 2 0 The Pragmatic Programmers Guide Fourth Edition Dave Thomas download

The document provides information about the book 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmer's Guide, Fourth Edition' by Dave Thomas, including download links and ISBN details. It also lists additional suggested ebooks related to programming and Ruby. The content covers various aspects of Ruby programming, including installation, classes, methods, and web development.

Uploaded by

jurakleelanr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
16 views

PDF Programming Ruby 1 9 2 0 The Pragmatic Programmers Guide Fourth Edition Dave Thomas download

The document provides information about the book 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmer's Guide, Fourth Edition' by Dave Thomas, including download links and ISBN details. It also lists additional suggested ebooks related to programming and Ruby. The content covers various aspects of Ruby programming, including installation, classes, methods, and web development.

Uploaded by

jurakleelanr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Programming Ruby 1 9 2 0 The Pragmatic


Programmers Guide Fourth Edition Dave Thomas

_____ Click the link below to download _____


https://ebookfinal.com/download/programming-
ruby-1-9-2-0-the-pragmatic-programmers-guide-fourth-
edition-dave-thomas/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Agile web development with rails a Pragmatic guide 1st


Edition Dave Thomas

https://ebookfinal.com/download/agile-web-development-with-rails-a-
pragmatic-guide-1st-edition-dave-thomas/

FXRuby Create Lean and Mean GUIs with Ruby Pragmatic


Programmers 1st Edition Lyle Johnson

https://ebookfinal.com/download/fxruby-create-lean-and-mean-guis-with-
ruby-pragmatic-programmers-1st-edition-lyle-johnson/

SAS Certification Prep Guide Advanced Programming for SAS


9 Fourth Edition Sas Institute

https://ebookfinal.com/download/sas-certification-prep-guide-advanced-
programming-for-sas-9-fourth-edition-sas-institute/

Pragmatic Unit Testing in C with NUnit Pragmatic


Programmers 1st Edition Andy Hunt

https://ebookfinal.com/download/pragmatic-unit-testing-in-c-with-
nunit-pragmatic-programmers-1st-edition-andy-hunt/
Programming Java 2 micro edition on Symbian OS a developer
s guide to MIDP 2 0 Martin De Jode

https://ebookfinal.com/download/programming-java-2-micro-edition-on-
symbian-os-a-developer-s-guide-to-midp-2-0-martin-de-jode/

Maple 9 advanced programming guide 1st Edition Monagan

https://ebookfinal.com/download/maple-9-advanced-programming-
guide-1st-edition-monagan/

Base SAS 9 1 Procedures Guide Volumes 1 2 3 and 4 1st


Edition Sas Institute

https://ebookfinal.com/download/base-sas-9-1-procedures-guide-
volumes-1-2-3-and-4-1st-edition-sas-institute/

Essential XNA Game Studio 2 0 Programming 1st Edition Jim


Perry

https://ebookfinal.com/download/essential-xna-game-
studio-2-0-programming-1st-edition-jim-perry/

Ruby Programming 1st Edition Jerry Lee Ford

https://ebookfinal.com/download/ruby-programming-1st-edition-jerry-
lee-ford/
Programming Ruby 1 9 2 0 The Pragmatic Programmers
Guide Fourth Edition Dave Thomas Digital Instant
Download
Author(s): Dave Thomas, Andy Hunt, Chad Fowler
ISBN(s): 9781937785499, 1937785491
Edition: Fourth Edition
File Details: PDF, 16.05 MB
Year: 2013
Language: english
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Programming Ruby 1.9 & 2.0
The Pragmatic Programmers’ Guide

Dave Thomas
with Chad Fowler
Andy Hunt

The Pragmatic Bookshelf


Dallas, Texas • Raleigh, North Carolina

Download from Wow! eBook <www.wowebook.com>


Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC
was aware of a trademark claim, the designations have been printed in initial capital letters or in all
capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic
Bookshelf, PragProg and the linking g device are trademarks of The Pragmatic Programmers, LLC.
Every precaution was taken in the preparation of this book. However, the publisher assumes no re-
sponsibility for errors or omissions, or for damages that may result from the use of information (in-
cluding program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team create better
software and have more fun. For more information, as well as the latest Pragmatic titles, please visit
us at http://pragprog.com.
The team that produced this book includes:
Janet Furlow (producer)
Juliet Benda (rights)
Ellie Callahan (support)

Copyright © 2013 The Pragmatic Programmers, LLC.


All rights reserved.

No part of this publication may be reproduced, 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-13: 978-1-93778-549-9
Encoded using the finest acid-free high-entropy binary digits.
Book version: P1.0—June, 2013

Download from Wow! eBook <www.wowebook.com>


Contents
Foreword to the Third Edition . . . . . . . . . . ix

Preface . . . . . . . . . . . . . . . . xi

Road Map . . . . . . . . . . . . . . . xv

Part I — Facets of Ruby


1. Getting Started . . . . . . . . . . . . . . 3
1.1 The Command Prompt 3
1.2 Installing Ruby 5
1.3 Running Ruby 9
1.4 Ruby Documentation: RDoc and ri 11

2. Ruby.new . . . . . . . . . . . . . . . 15
2.1 Ruby Is an Object-Oriented Language 15
2.2 Some Basic Ruby 17
2.3 Arrays and Hashes 20
2.4 Symbols 21
2.5 Control Structures 23
2.6 Regular Expressions 24
2.7 Blocks and Iterators 25
2.8 Reading and ’Riting 27
2.9 Command-Line Arguments 28
2.10 Onward and Upward 28

3. Classes, Objects, and Variables . . . . . . . . . . 29


3.1 Objects and Attributes 32
3.2 Classes Working with Other Classes 37
3.3 Access Control 40
3.4 Variables 43

4. Containers, Blocks, and Iterators . . . . . . . . . . 45


4.1 Arrays 45
4.2 Hashes 47
4.3 Blocks and Iterators 52
4.4 Containers Everywhere 68

Download from Wow! eBook <www.wowebook.com>


Contents • iv

5. Sharing Functionality: Inheritance, Modules, and Mixins . . . . 69


5.1 Inheritance and Messages 69
5.2 Modules 73
5.3 Mixins 75
5.4 Iterators and the Enumerable Module 77
5.5 Composing Modules 77
5.6 Inheritance, Mixins, and Design 80

6. Standard Types . . . . . . . . . . . . . . 83
6.1 Numbers 83
6.2 Strings 86
6.3 Ranges 90

7. Regular Expressions . . . . . . . . . . . . . 93
7.1 What Regular Expressions Let You Do 93
7.2 Ruby’s Regular Expressions 94
7.3 Digging Deeper 96
7.4 Advanced Regular Expressions 105

8. More About Methods . . . . . . . . . . . . 115


8.1 Defining a Method 115
8.2 Calling a Method 118

9. Expressions . . . . . . . . . . . . . . 125
9.1 Operator Expressions 126
9.2 Miscellaneous Expressions 127
9.3 Assignment 128
9.4 Conditional Execution 132
9.5 case Expressions 136
9.6 Loops 138
9.7 Variable Scope, Loops, and Blocks 142

10. Exceptions, catch, and throw . . . . . . . . . . 145


10.1 The Exception Class 145
10.2 Handling Exceptions 146
10.3 Raising Exceptions 150
10.4 catch and throw 151

11. Basic Input and Output . . . . . . . . . . . . 153


11.1 What Is an IO Object? 153
11.2 Opening and Closing Files 153
11.3 Reading and Writing Files 154
11.4 Talking to Networks 158
11.5 Parsing HTML 159

12. Fibers, Threads, and Processes . . . . . . . . . . 161


12.1 Fibers 161
12.2 Multithreading 163
12.3 Controlling the Thread Scheduler 167

Download from Wow! eBook <www.wowebook.com>


Contents •v

12.4 Mutual Exclusion 167


12.5 Running Multiple Processes 170

13. Unit Testing . . . . . . . . . . . . . . 175


13.1 The Testing Framework 177
13.2 Structuring Tests 181
13.3 Organizing and Running Tests 183
13.4 RSpec and Shoulda 186
13.5 Test::Unit assertions 193

14. When Trouble Strikes! . . . . . . . . . . . . 195


14.1 Ruby Debugger 195
14.2 Interactive Ruby 196
14.3 Editor Support 197
14.4 But It Doesn’t Work! 198
14.5 But It’s Too Slow! 201

Part II — Ruby in Its Setting


15. Ruby and Its World . . . . . . . . . . . . 209
15.1 Command-Line Arguments 209
15.2 Program Termination 214
15.3 Environment Variables 214
15.4 Where Ruby Finds Its Libraries 216
15.5 RubyGems Integration 217
15.6 The Rake Build Tool 222
15.7 Build Environment 224

16. Namespaces, Source Files, and Distribution . . . . . . . 225


16.1 Namespaces 225
16.2 Organizing Your Source 226
16.3 Distributing and Installing Your Code 233

17. Character Encoding . . . . . . . . . . . . 239


17.1 Encodings 240
17.2 Source Files 240
17.3 Transcoding 245
17.4 Input and Output Encoding 246
17.5 Default External Encoding 248
17.6 Encoding Compatibility 249
17.7 Default Internal Encoding 250
17.8 Fun with Unicode 251

18. Interactive Ruby Shell . . . . . . . . . . . . 253


18.1 Command Line 253
18.2 Commands 260

19. Documenting Ruby . . . . . . . . . . . . 263


19.1 Adding RDoc to Ruby Code 266
19.2 Adding RDoc to C Extensions 269

Download from Wow! eBook <www.wowebook.com>


Contents • vi

19.3 Running RDoc 271


19.4 Ruby source file documented with RDoc 272
19.5 C source file documented with RDoc 274

20. Ruby and the Web . . . . . . . . . . . . . 277


20.1 Writing CGI Scripts 277
20.2 Using cgi.rb 277
20.3 Templating Systems 280
20.4 Cookies 284
20.5 Choice of Web Servers 286
20.6 Frameworks 287

21. Ruby and Microsoft Windows . . . . . . . . . . 289


21.1 Running Ruby Under Windows 289
21.2 Win32API 289
21.3 Windows Automation 290

Part III — Ruby Crystallized


22. The Ruby Language . . . . . . . . . . . . 297
22.1 Source File Encoding 297
22.2 Source Layout 297
22.3 The Basic Types 299
22.4 Names 306
22.5 Variables and Constants 308
22.6 Expressions, Conditionals, and Loops 316
22.7 Method Definition 323
22.8 Invoking a Method 327
22.9 Aliasing 330
22.10 Class Definition 331
22.11 Module Definitions 333
22.12 Access Control 335
22.13 Blocks, Closures, and Proc Objects 335
22.14 Exceptions 339
22.15 catch and throw 341

23. Duck Typing . . . . . . . . . . . . . . 343


23.1 Classes Aren’t Types 344
23.2 Coding like a Duck 348
23.3 Standard Protocols and Coercions 349
23.4 Walk the Walk, Talk the Talk 355

24. Metaprogramming . . . . . . . . . . . . . 357


24.1 Objects and Classes 357
24.2 Singletons 360
24.3 Inheritance and Visibility 365
24.4 Modules and Mixins 366
24.5 Metaprogramming Class-Level Macros 372
24.6 Two Other Forms of Class Definition 377

Download from Wow! eBook <www.wowebook.com>


Contents • vii

24.7 instance_eval and class_eval 379


24.8 Hook Methods 383
24.9 One Last Example 388
24.10 Top-Level Execution Environment 390
24.11 The Turtle Graphics Program 391

25. Reflection, ObjectSpace, and Distributed Ruby . . . . . . 393


25.1 Looking at Objects 393
25.2 Looking at Classes 394
25.3 Calling Methods Dynamically 396
25.4 System Hooks 398
25.5 Tracing Your Program’s Execution 400
25.6 Behind the Curtain: The Ruby VM 402
25.7 Marshaling and Distributed Ruby 403
25.8 Compile Time? Runtime? Anytime! 408

26. Locking Ruby in the Safe . . . . . . . . . . . 409


26.1 Safe Levels 410
26.2 Tainted Objects 410
26.3 Trusted Objects 411
26.4 Definition of the safe levels 412

Part IV — Ruby Library Reference


27. Built-in Classes and Modules . . . . . . . . . . 417

28. Standard Library . . . . . . . . . . . . . 729

A1. Support . . . . . . . . . . . . . . . 829


A1.1 Web Sites 829
A1.2 Usenet Newsgroup 830
A1.3 Mailing Lists 830
A1.4 Bug Reporting 830

A2. Bibliography . . . . . . . . . . . . . . 831

Index . . . . . . . . . . . . . . . . 833

Download from Wow! eBook <www.wowebook.com>


Foreword to the Third Edition
I wrote forewords to the previous two editions of this book. For the first edition, I wrote
about motivation. For the second edition, I wrote about miracles.
For this third edition, I’d like to write about courage. I always admire brave people. People
around Ruby seem to be brave, like the authors of this book. They were brave to jump in to
a relatively unknown language like Ruby. They were brave to try new technology. They
could have happily stayed with an old technology, but they didn’t. They built their own
world using new bricks and mortar. They were adventurers, explorers, and pioneers. By
their effort, we have a fruitful result—Ruby.
Now, I feel that I’ve created my own universe with help from those brave people. At first, I
thought it was a miniature universe, like the one in “Fessenden’s Worlds.” But now it seems
like a real universe. Countless brave people are now working with Ruby. They challenge
new things every day, trying to make the world better and bigger. I am very glad I am part
of the Ruby world.
I suppose that even the world itself could not contain the books that should be written. But
now we have the first book, updated to the most recent. Enjoy.

Yukihiro Matsumoto, aka “Matz”


Japan, February 2009

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Preface
This book is a new version of the PickAxe, as Programming Ruby is known to Ruby program-
mers. It is a tutorial and reference for versions 1.9 and 2.0 of the Ruby programming language.
Ruby 1.9 was a significant departure from previous versions. There are major changes in
string handling, the scoping of block variables, and the threading model. It has a new virtual
machine. The built-in libraries have grown, adding many hundreds of new methods and
almost a dozen new classes. The language now supports scores of character encodings,
making Ruby one of the only programming languages to live fully in the whole world.
Ruby 2.0 is a (fairly minor) incremental improvement on Ruby 1.9.

Why Ruby?
When Andy and I wrote the first edition, we had to explain the background and appeal of
Ruby. Among other things, we wrote, “When we discovered Ruby, we realized that we’d
found what we’d been looking for. More than any other language with which we have
worked, Ruby stays out of your way. You can concentrate on solving the problem at hand,
instead of struggling with compiler and language issues. That’s how it can help you become
a better programmer: by giving you the chance to spend your time creating solutions for
your users, not for the compiler.”
That belief is even stronger today. More than thirteen years later, Ruby is still my language
of choice: I use it for client applications and web applications. I use it to run our publishing
business (our online store, http://pragprog.com, is more than 40,000 lines of Rails code), and I
use it for all those little programming jobs I do just to get things running smoothly.
In all those years, Ruby has progressed nicely. A large number of methods have been added
to the built-in classes and modules, and the size of the standard library (those libraries
included in the Ruby distribution) has grown tremendously. The community now has a
standard documentation system (RDoc), and RubyGems has become the system of choice
for packaging Ruby code for distribution. We have a best-of-breed web application frame-
work, Ruby on Rails, with others waiting in the wings. We are leading the world when it
comes to testing, with tools such as RSpec and Cucumber, and we’re working through the
hard problems of packaging and dependency management. We’ve matured nicely.
But Ruby is older than that. The first release of this book happened on Ruby’s 20th birthday
(it was created on February 24, 1993). The release of Ruby 2.0 is a celebration of that
anniversary.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Preface • xii

Ruby Versions
1
This version of the PickAxe documents both Ruby 2.0 and Ruby 1.9.3.
Exactly what version of Ruby did I use to write this book? Let’s ask Ruby:
$ ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.2.0]

This illustrates an important point. Most of the code samples you see in this book are actually
executed each time I format the book. When you see some output from a program, that
output was produced by running the code and inserting the results into the book.

Changes in the Book


Throughout the book I’ve tried to mark differences between Ruby 1.9 and 2.0 using a small
symbol, like the one here. If you’re reading this as an ebook, you’ll see little arrows next to
New in 2.0⇣ this flag. Clicking those will take you to the next or previous 2.0 change. One change I didn’t
make: I decided to continue to use the word we when talking about the authors in the body
of the book. Many of the words come from the first edition, and I certainly don’t want to
claim any credit for Andy’s work on that book.

Changes in the Ruby 2.0 Printing


Compared to the major change that occurred between Ruby 1.8 and Ruby 1.9, the update to
Ruby 2 is fairly gentle. This book documents all the updated builtin class changes and the
new keyword arguments. It spends some time looking at lazy enumerators, and at the
updates to the regular expression engine. But, in general, users of Ruby 1.9 will feel right at
home, and folks still using Ruby 1.8 should consider skipping straight to Ruby 2.

Resources
Visit the Ruby website at http://www.ruby-lang.org to see what’s new. Chat with other Ruby
users on the newsgroup or mailing lists (see Appendix 1, Support, on page 829).
And I’d certainly appreciate hearing from you. Comments, suggestions, errors in the text,
and problems in the examples are all welcome. Email us at rubybook@pragprog.com.
2
If you find errors in the book, you can add them to the errata page. If you’re reading the
PDF version of the book, you can also report an erratum by clicking the link in the page
footers.
You’ll find links to the source code for almost all the book’s example code at http://www.prag-
prog.com/titles/ruby4.

1. Ruby version numbering used to follow the same scheme used for many other open source projects.
Releases with even minor version numbers—1.6, 1.8, and so on—were stable, public releases. These
are the releases that are prepackaged and made available on the various Ruby websites. Development
versions of the software had odd minor version numbers, such as 1.5 and 1.7. However, in 2007 Matz
broke with convention and made 1.9 a stable public release of Ruby.
2. http://www.pragprog.com/titles/ruby4/errata.html

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Acknowledgments • xiii

Acknowledgments
The first International Ruby Conference had something like 32 attendees. We could all fit
into the tiny hotel bar and talk the night away. Things have changed. The annual conference
now sells out many hundreds of seats within hours, and an increasing number of secondary
conferences have sprung up to meet the needs of folks who can’t get to RubyConf.
As the community has grown, so has Ruby. The language and its libraries are now many
times bigger than they were back when the first edition of this book came out.
And as the language has grown, so has this book. The PickAxe is now massive, mostly
because I still want to document every single built-in class, module, and method. But a book
of this size can never be a solo undertaking. This edition builds on the work from the first
two editions, which included major contributions from Chad Fowler and Andy Hunt. Just
as significant, all three editions have been works created by the Ruby community. On the
mailing lists, in the forums, and on this book’s errata pages, hundreds of people have con-
tributed ideas, code, and corrections to make it better. As always, I owe every one of you a
big “thank you!” for all you have done and for all that you do. The Ruby community is still
as vibrant, interesting, and (mostly) friendly as it ever was—that’s quite an achievement
given the explosive growth we’ve enjoyed.
For the third (tenth anniversary) printing, Wayne E. Seguin was kind enough to check the
section on the wonderful tool RVM, and Luis Lavena checked the section on installing under
Windows, as well as the chapter on running Ruby on Windows. And I’d like to call Anthony
Burns a hero for doing an amazing job of reading through the changes as I was writing them,
3
but that would take away from the fact that he’s a true hero.
Getting this book into production has also been a challenge. Kim Wimpsett is the world’s
best copy editor—she’s the only copy editor I know who finds errors in code and fixes XML
markup. Any remaining errors in this book are a result of my mistyping her suggested cor-
rections. And, as we raced to get the book to the printer in time for RubyConf X, Janet Furlow
patiently kept us all on track.
Finally, I’m still deeply indebted to Yukihiro “Matz” Matsumoto, the creator of Ruby.
Throughout this prolonged period of growth and change, he has remained helpful, cheery,
and dedicated to polishing this gem of a language. The friendly and open spirit of the Ruby
community is a direct reflection of the person at its center.
Thank you all. Domo arigato gozaimasu.

Dave Thomas
The Pragmatic Programmers
dave@pragprog.com
June 2013

3. http://www.flickr.com/photos/pragdave/sets/72157625046498937/

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Preface • xiv

Notation Conventions
Literal code examples are shown using a sans-serif font:
class SampleCode
def run
#...
end
end

Within the text, Fred#do_something is a reference to an instance method (in this case the method
4
do_something) of class Fred, Fred.new is a class method, and Fred::EOF is a class constant. The
decision to use a hash character to indicate instance methods was a tough one. It isn’t valid
Ruby syntax, but we thought that it was important to differentiate between the instance and
class methods of a particular class. When you see us write File.read, you know we’re talking
about the class method read. When instead we write File#read, we’re referring to the instance
method read. This convention is now standard in most Ruby discussions and documentation.
This book contains many snippets of Ruby code. Where possible, we’ve tried to show what
happens when they run. In simple cases, we show the value of expressions on the same line
as the expression. Here’s an example:
a = 1
b = 2
a + b # => 3

Here, you can see that the result of evaluating a + b is the value 3, shown to the right of the
arrow. Note that if you were to run this program, you wouldn’t see the value 3 output—
you’d need to use a method such as puts to write it out.
At times, we’re also interested in the values of assignment statements:
a = 1 # => 1
a + 2 # => 3

If the program produces more complex output, we show it after the program code:
3.times { puts "Hello!" }
produces:
Hello!
Hello!
Hello!

In some of the library documentation, we wanted to show where spaces appear in the output.
You’ll see these spaces as ␣ characters.
Command-line invocations are shown with literal text in a regular font, and parameters you
supply are shown in an italic font. Optional elements are shown in brackets.
ruby ‹ flags ›* progname ‹ arguments ›*

4. In some other Ruby documentation, you may see class methods written as Fred::new. This is perfectly
valid Ruby syntax; we just happen to think that Fred.new is less distracting to read.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Road Map
The main text of this book has four separate parts, each with its own personality and each
addressing different aspects of the Ruby language.
In Part I, Facets of Ruby, you’ll find a Ruby tutorial. It starts with some notes on getting Ruby
running on your system followed by a short chapter on some of the terminology and concepts
that are unique to Ruby. This chapter also includes enough basic syntax so that the other
chapters will make sense. The rest of the tutorial is a top-down look at the language. There
we talk about classes and objects, types, expressions, and all the other things that make up
the language. We end with chapters on unit testing and digging yourself out when trouble
strikes.
One of the great things about Ruby is how well it integrates with its environment. Part II,
Ruby in Its Setting, investigates this. Here you’ll find practical information on using Ruby:
using the interpreter options, using irb, documenting your Ruby code, and packaging your
Ruby gems so that others can enjoy them. You’ll also find tutorials on some common Ruby
tasks: using Ruby with the Web and using Ruby in a Microsoft Windows environment
(including wonderful things such as native API calls, COM integration, and Windows
Automation). We’ll also touch on using Ruby to access the Internet.
Part III, Ruby Crystallized, contains more advanced material. Here you’ll find all the gory
details about the language, the concept of duck typing, the object model, metaprogramming,
tainting, reflection, and marshaling. You could probably speed-read this the first time through,
but we think you’ll come back to it as you start to use Ruby in earnest.
The Ruby Library Reference is Part IV. It’s big. We document more than 1,300 methods in 57
built-in classes and modules (up from 800 methods in 40 classes and modules in the previous
edition). On top of that, we now document the library modules that are included in the
standard Ruby distribution (98 of them).
So, how should you read this book? Well, depending on your level of expertise with pro-
gramming in general and OO in particular, you may initially want to read just a few portions
of the book. Here are our recommendations.
If you’re a beginner, you may want to start with the tutorial material in Part I. Keep the
library reference close at hand as you start to write programs. Get familiar with the basic
classes such as Array, Hash, and String. As you become more comfortable in the environment,
you may want to investigate some of the more advanced topics in Part III.
If you’re already comfortable with Perl, Python, Java, or Smalltalk, then we suggest reading
Chapter 1, Getting Started, on page 3, which talks about installing and running Ruby, fol-
lowed by the introduction in Chapter 2, Ruby.new, on page 15. From there, you may want

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Road Map • xvi

to take the slower approach and keep going with the tutorial that follows, or you can skip
ahead to the gritty details starting in Part III, followed by the library reference in Part IV.
Experts, gurus, and “I-don’t-need-no-stinking-tutorial” types can dive straight into the lan-
guage reference in Chapter 22, The Ruby Language, on page 297; skim the library reference;
and then use the book as a (rather attractive) coffee coaster.
Of course, nothing is wrong with just starting at the beginning and working your way
through page by page.
And don’t forget, if you run into a problem that you can’t figure out, help is available. For
more information, see Appendix 1, Support, on page 829.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Part I

Facets of Ruby

Download from Wow! eBook <www.wowebook.com>


CHAPTER 1

Getting Started
Before we start talking about the Ruby language, it would be useful if we helped you get
Ruby running on your computer. That way, you can try sample code and experiment on
your own as you read along. In fact, that’s probably essential if you want to learn Ruby—
get into the habit of writing code as you’re reading. We will also show you some different
ways to run Ruby.

1.1 The Command Prompt


(Feel free to skip to the next section if you’re already comfortable at your system’s command
prompt.)
Although there’s growing support for Ruby in IDEs, you’ll probably still end up spending
some time at your system’s command prompt, also known as a shell prompt or just plain
prompt. If you’re a Linux user, you’re probably already familiar with the prompt. If you don’t
already have a desktop icon for it, hunt around for an application called Terminal or xterm.
(On Ubuntu, you can navigate to it using Applications → Accessories → Terminal.) On
Windows, you’ll want to run cmd.exe, accessible by typing cmd into the dialog box that appears
when you select Start → Run. On OS X, run Applications → Utilities → Terminal.app.
In all three cases, a fairly empty window will pop up. It will contain a banner and a prompt.
Try typing echo hello at the prompt and hitting Enter (or Return, depending on your keyboard).
You should see hello echoed back, and another prompt should appear.

Directories, Folders, and Navigation


It is beyond the scope of this book to teach the commands available at the prompt, but we
do need to cover the basics of finding your way around.
If you’re used to a GUI tool such as Explorer on Windows or Finder on OS X for navigating
to your files, then you’ll be familiar with the idea of folders—locations on your hard drive
that can hold files and other folders.
When you’re at the command prompt, you have access to these same folders. But, somewhat
confusingly, at the prompt these folders are called directories (because they contain lists of
other directories and files). These directories are organized into a strict hierarchy. On Unix-
based systems (including OS X), there’s one top-level directory, called / (a forward slash).
On Windows, there is a top-level directory for each drive on your system, so you’ll find the
top level for your C: drive at C:\ (that’s the drive letter C, a colon, and a backslash).

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 1. Getting Started •4

The path to a file or directory is the set of directories that you have to traverse to get to it
from the top-level directory, followed by the name of the file or directory itself. Each compo-
nent in this name is separated by a forward slash (on Unix) or a backslash (on Windows).
So, if you organized your projects in a directory called projects under the top-level directory
and if the projects directory had a subdirectory for your time_planner project, the full path to
the README file would be /projects/time_planner/readme.txt on Unix and C:\projects\time_plan-
ner\readme.txt on Windows.

Spaces in Directory Names and Filenames


Most operating systems now allow you to create folders with spaces in their names. This is great when
you’re working at the GUI level. However, from the command prompt, spaces can be a headache,
because the shell that interprets what you type will treat the spaces in file and folder names as being
parameter separators and not as part of the name. You can get around this, but it generally isn’t worth
the hassle. If you are creating new folders and files, it’s easiest to avoid spaces in their names.

To navigate to a directory, use the cd command. (Because the Unix prompt varies from system
to system, we’ll just use a single dollar sign to represent it here.)
$ cd /projects/time_planner (on Unix)
C:\> cd \projects\time_planner (on Windows)

On Unix boxes, you probably don’t want to be creating top-level directories. Instead, Unix
gives each user their own home directory. So, if your username is dave, your home directory
might be located in /usr/dave, /home/dave, or /Users/dave. At the shell prompt, the special char-
acter ~ (a single tilde) stands for the path to your home directory. You can always change
directories to your home directory using cd ~, which can also be abbreviated to just cd.
To find out the directory you’re currently in, you can type pwd (on Unix) or cd on Windows.
So, for Unix users, you could type this:
$ cd /projects/time_planner
$ pwd
/projects/time_planner
$ cd
$ pwd
/Users/dave

On Windows, there’s no real concept of a user’s home directory:


C:\> cd \projects\time_planner
C:\projects\time_planner> cd \projects
C:\projects>

You can create a new directory under the current directory using the mkdir command:
$ cd /projects
$ mkdir expense_tracker
$ cd expense_tracker
$ pwd
/projects/expense_tracker

Notice that to change to the new directory, we could just give its name relative to the current
directory—we don’t have to enter the full path.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Installing Ruby •5

We suggest you create a directory called pickaxe to hold the code you write while reading
this book:
$ mkdir ~/pickaxe (on Unix)
C:\> mkdir \pickaxe (on Windows)

Get into the habit of changing into that directory before you start work:
$ cd ~/pickaxe (on Unix)
C:\> cd \pickaxe (on Windows)

1.2 Installing Ruby


Ruby comes preinstalled on many Linux distributions, and Mac OS X includes Ruby (although
the version of Ruby that comes with OS X is normally several releases behind the current
Ruby version). Try typing ruby -v at a command prompt—you may be pleasantly surprised.
If you don’t already have Ruby on your system or if you’d like to upgrade to a newer version
(remembering that this book describes Ruby 1.9 and Ruby 2.0), you can install it pretty
simply. What you do next depends on your operating system.

Installing on Windows
There are two options for installing Ruby on Windows. The first is a simple installer pack-
age—download it, and you’ll have Ruby up and running in minutes. The second is slightly
more complex but gives you the flexibility of easily managing multiple Ruby environments
on the same computer at the same time. Whichever option you choose, you’ll first need to
download and install a working Ruby.

Install Ruby with RubyInstaller


The simple solution (and probably the right one to use if you’re not planning on running
multiple versions of Ruby at the same time) is Luis Lavena’s RubyInstaller.org.
Simply navigate to http://rubyinstaller.org, click the big DOWNLOAD button, and select the
Ruby version you want. Save the file to your downloads folder, and then run it once it has
downloaded. Click through the Windows nanny warnings, and you’ll come to a conventional
installer. Accept the defaults, and when the installer finishes, you’ll have an entry for Ruby
in your All Programs menu of the Start menu:

Select Start Command Prompt with Ruby to open a copy of the Windows command shell with
the environment set up to run Ruby.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 1. Getting Started •6

pik: Install Multiple Ruby Environments


The pik system by Gordon Thiesfeld allows you to manage multiple Ruby interpreters on
the same machine, switching between them easily. Obviously, this isn’t something everyone
needs, so you may want to skip to Source Code from This Book on page 9.
Before you start, make sure you have a working Ruby on your machine, using the instructions
from the previous section to download and use RubyInstaller if necessary.
Then, install pik. Visit http://github.com/vertiginous/pik/downloads. Look near the top for the list
of .msi files, and choose the latest. Double-click the filename to download and install it.
After a few seconds, the Pik Setup dialog box will appear. Accept the defaults, and pik will
be installed.
At this time, you’ll probably need to either log out and log back in or (possibly) restart
Windows to get pik successfully integrated into your environment.
Now bring up a Ruby command prompt (Start Command Prompt with Ruby), and type the
following at the prompt:
C:\Users\dave> pik add
** Adding: 193: ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

You’ve now registered that Ruby interpreter with pik. At any other command prompt, you
can use the pik command to list the Ruby interpreters pik knows about and to tell pik to
make a particular interpreter current:
C:\>pik list
193: ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

C:\>pik use 193

C:\>ruby -v
ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

Having gotten one Ruby registered with pik, let’s install another. We’ll play with JRuby, an
implementation of Ruby written in Java. Before doing this, you’ll need to download the Java
runtime (Google is your friend). Once Java is installed, tell pik to install the JRuby interpreter:
C:\> pik install jruby
** Downloading: http://jruby.org......downloads/1.5.2/jruby-bin-1.5.2.zip
to: C:\Users\dave\.pik\downloads\jruby-bin-1.5.2.zip
** Extracting: C:\Users\dave\.pik\downloads\jruby-bin-1.5.2.zip
to: C:\Users\dave\.pik\rubies\JRuby-152
done

** Adding: 152: jruby 1.5.2 (ruby 1.8.7 patchlevel 249) (2010-08-20 1c5e29d)
(Java HotSpot(TM) Client VM 1.6.0_21) [x86-java]
Located at: C:\Users\dave\.pik\rubies\JRuby-152\bin

You now have two Ruby interpreters managed by pik. You can switch between them at the
command line:
C:\>pik list
152: jruby 1.5.2 (ruby 1.8.7 patchlevel 249) (2010-08-20 1c5e29d) (Java H...
193: ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Installing Ruby •7

C:\>pik use 152


C:\>jruby -v
jruby 1.5.2 (ruby 1.8.7 patchlevel 249) (2010-08-20 1c5e29d)
(Java HotSpot(TM) Client VM 1.6.0_21) [x86-java]

C:\>pik use 193


C:\>ruby -v
ruby 1.9.3p0 (2011-10-30) [i386-mingw32]

If you plan on installing gems that have native code components (that is, they interface to
existing Windows libraries using C code), you’ll need a C development environment on
your machine, and you’ll need to download and install the Pik development kit.
Now that you’re all set up, skip forward to Source Code from This Book on page 9.

Installing on Linux and Mac OS X


One of the interesting things about the various Unix-like systems out there is that their
maintainers all have their own ideas about how to package tools such as Ruby. It is very
nice that they have gone to this trouble, but it also means that if you go with the flow, you’ll
need to learn their way of doing things. It also often means that you’ll be stuck with what
you’re given. So, we’re going to take a different approach. We’re going to use a system called
the Ruby Version Manager (RVM), written by Wayne E. Seguin. RVM is a tool that lets you
have multiple independent Ruby installations on the same machine. You can switch between
them using a single command. This is wonderful, because you can experiment with new
versions of Ruby while still keeping the old ones on your system. We use RVM to keep a
1
Ruby environment for the examples in this book that’s isolated from our daily work.

Installing RVM
Although you can install RVM using RubyGems (assuming you already have a working
Ruby on your system), the preferred approach is to install it directly.
2
Most Unix-like systems will already have all the dependencies installed. The possible fly
in the ointment is Ubuntu, where the curl utility is not installed by default. Add it before you
start with this:
$ sudo apt-get update
$ sudo apt-get install curl

You install RVM by executing a script that you download from its repository in github.
$ curl -L https://get.rvm.io | bash -s stable

If this makes you nervous, you can always download the script first, inspect it, and then run
it.
$ curl -L get.rvm.io >rvm-installer
$ less rvm-installer
$ bash rvm-installer

1. RVM isn’t the only way of managing multiple Ruby installations. You might want to look at rbenv
(https://github.com/sstephenson/rbenv/) or chruby (https://github.com/postmodern/chruby).
2. http://rvm.io/rvm/prerequisites/

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 1. Getting Started •8

Behind the scenes, either option fetches a script from the RVM git repository and executes
it on your local box. The end result is that RVM is installed in a directory named .rvm beneath
your home directory. At the end of the process, RVM spits out a page or so of information.
You should read it.
You may need to knit RVM into your environment. To find out, have a look at the end of
~/.bashrc. If it doesn’t mention RVM, add the following:

source $HOME/.rvm/scripts/rvm

Once that’s done, start a new terminal window (because RVM gets loaded only when your
3
.bashrc file executes). Type rvm help, and you should get a summary of RVM usage.

Before we use RVM to install Ruby, we have to let it install a few things that it will need. To
do that, we need to let RVM install various system libraries and utilities that are used when
building Ruby. First, we have to give it permission to manage packages:
dave@ubuntu:~$ rvm autolibs packages
4
If you run into problems, Wayne has a great set of hints on the RVM installation page.

Installing Ruby 2.0 Under RVM


This is where we start to see the payoff. Let’s install Ruby 2.0. (Note that in the following
commands we do not type sudo. One of the joys of RVM is that it does everything inside
your home directory—you don’t have to be privileged to install or use new Ruby versions.)
$ rvm install 2.0.0

RVM first installs the system packages it needs (if any). At this stage, you may be prompted
5
to enter a password that gives you superuser privileges.
RVM then downloads the appropriate source code and builds Ruby 2.0. It also installs a few
tools (including irb, RDoc, ri, and RubyGems). Be patient—the process may take five minutes
or so. Once it finishes, you’ll have Ruby 2.0 installed. To use it, type the following:
dave@ubuntu:~$ rvm use 2.0.0
info: Using ruby 2.0.0
dave@ubuntu:~$ ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [i686-linux]

This is probably more work than you were expecting. If all you wanted to do was install a
prepacked Ruby, we’d agree. But what you’ve really done here is given yourself an incredible
amount of flexibility. Maybe in the future a project comes along that requires that you use
Ruby 1.8.7. That’s not a problem—just use rvm install 1.8.7 to install it, and use rvm use 1.8.7
to switch to it.
The rvm use command applies only to the current terminal session. If you want to make it
apply to all your sessions, issue this command:
$ rvm use --default 2.0.0

3. The website, http://rvm.io/, has even more information.


4. http://rvm.io/rvm/install/
5. This is the only time you’ll need these privileges. Once your system has all the tools it needs, RVM can
do the rest of its work as a regular user.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Running Ruby •9

The RubyGems that you install while you’re using an RVM-installed Ruby will be added to
that version of Ruby and not installed globally. Do not prepend the gem install command
with a sudo—bad things will happen.

Why Stop with Ruby 2.0?


As well as installing stable versions of the Matz Ruby interpreter, RVM will also manage interpreters
from different sources (JRuby, Rubinius, Ruby Enterprise Edition, and so on—rvm list known gives the
full list). It will also install versions of Ruby directly from the developers’ repository—versions that
are not official releases.

The Ruby developers use Subversion (often abbreviated as SVN) as their revision control system, so
you’ll need a Subversion client installed on your machine. Once done, you can use RVM to install the
very latest Ruby using rvm install ruby-head or the latest version of the 2.0 branch using rvm install 2.0-
head.

Source Code from This Book


If a code listing is preceded by a filename in a shaded bar, the source is available for down-
6
load. Sometimes, the listings of code in the book correspond to a complete source file. Other
times, the book shows just part of the source in a file—the program file may contain addi-
tional scaffolding to make the code run.
If you’re reading this as an ebook, you can download the code for an example by clicking
the heading.

1.3 Running Ruby


Now that Ruby is installed, you’d probably like to run some programs. Unlike compiled
languages, you have two ways to run Ruby—you can type in code interactively, or you can
create program files and run them. Typing in code interactively is a great way to experiment
with the language, but for code that’s more complex or that you will want to run more than
once, you’ll need to create program files and run them. But, before we go any further, let’s
7
test to see whether Ruby is installed. Bring up a fresh command prompt, and type this:
$ ruby -v
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.2.0]

If you believe that you should have Ruby installed and yet you get an error saying something
like “ruby: command not found,” then it is likely that the Ruby program is not in your path
—the list of places that the shell searches for programs to run. If you used the Windows
One-Click Installer, make sure you rebooted before trying this command. If you’re on Linux
or OS X and you’re using RVM, make sure you type rvm use 2.0 before trying to use Ruby.

Interactive Ruby
One way to run Ruby interactively is simply to type ruby at the shell prompt. Here we typed
in the single puts expression and an end-of-file character (which is Ctrl+D on our system).

6. http://pragprog.com/titles/ruby4/code
7. Remember, you may need to use ruby1.9 as the command name if you installed using a package man-
agement system.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 1. Getting Started • 10

This process works, but it’s painful if you make a typo, and you can’t really see what’s going
on as you type.
$ ruby
puts "Hello, world!"
^D
Hello, world!

For most folks, irb—Interactive Ruby—is the tool of choice for executing Ruby interactively.
irb is a Ruby shell, complete with command-line history, line-editing capabilities, and job
control. (In fact, it has its own chapter: Chapter 18, Interactive Ruby Shell, on page 253.) You
run irb from the command line. Once it starts, just type in Ruby code. It will show you the
value of each expression as it evaluates it. Exit an irb session by typing exit or by using the
Ctrl+D.
$ irb
2.0.0 :001 > def sum(n1, n2)
2.0.0 :002?> n1 + n2
2.0.0 :003?> end
=> nil
2.0.0 :004 > sum(3,4)
=> 7
2.0.0 :005 > sum("cat", "dog")
=> "catdog"
2.0.0 :006 > exit

We recommend that you get familiar with irb so you can try our examples interactively.

Ruby Programs
The normal way to write Ruby programs is to put them in one or more files. You’ll use a
text editor (Emacs, vim, Sublime, and so on) or an IDE (such as NetBeans) to create and
maintain these files. You’ll then run the files either from within the editor or IDE or from
the command line. I personally use both techniques, typically running from within the editor
for single-file programs and from the command line for more complex ones.
Let’s start by creating a simple Ruby program and running it. Open a command window,
and navigate to the pickaxe directory you created earlier:
$ cd ~/pickaxe (unix)
C:\> cd \pickaxe (windows)

Then, using your editor of choice, create the file myprog.rb, containing the following text.
gettingstarted/myprog.rb
puts "Hello, Ruby Programmer"
puts "It is now #{Time.now}"

(Note that the second string contains the text Time.now between curly braces, not parentheses.)
You can run a Ruby program from a file as you would any other shell script, Perl program,
or Python program. Simply run the Ruby interpreter, giving it the script name as an argument:
$ ruby myprog.rb
Hello, Ruby Programmer
It is now 2013-05-27 12:30:36 -0500

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Ruby Documentation: RDoc and ri • 11
8
On Unix systems, you can use the “shebang” notation as the first line of the program file:
#!/usr/bin/ruby
puts "Hello, Ruby Programmer"
puts "It is now #{Time.now}"

If you make this source file executable (using, for instance, chmod +x myprog.rb), Unix lets you
run the file as a program:
$ ./myprog.rb
Hello, Ruby Programmer
It is now 2013-05-27 12:30:36 -0500

You can do something similar under Microsoft Windows using file associations, and you
can run Ruby GUI applications by double-clicking their names in Windows Explorer.

1.4 Ruby Documentation: RDoc and ri


As the volume of the Ruby libraries has grown, it has become impossible to document them
all in one book; the standard library that comes with Ruby now contains more than 9,000
methods. Fortunately, an alternative to paper documentation exists for these methods (and
classes and modules). Many are now documented internally using a system called RDoc.
If a source file is documented using RDoc, its documentation can be extracted and converted
into HTML and ri formats.
9
Several websites contain a complete set of the RDoc documentation for Ruby. Browse on
over, and you should be able to find at least some form of documentation for any Ruby
library. The sites are adding new documentation all the time.
The ri tool is a local, command-line viewer for this same documentation. Most Ruby distri-
10
butions now also install the resources used by the ri program.
To find the documentation for a class, type ri ClassName. For example, the following is the
summary information for the GC class. (To get a list of classes with ri documentation, type
ri with no arguments.)

$ ri GC
-----------------------------------------------------------------------------------
The GC module provides an interface to Ruby's garbage collection mechanism. Some of
the underlying methods are also available via the ObjectSpace module.

You may obtain information about the operation of the GC through GC::Profiler.
-----------------------------------------------------------------------------------
Class methods:
count, disable, enable, malloc_allocated_size, malloc_allocations,
start, stat, stress, stress=

Instance methods:
garbage_collect

8. If your system supports it, you can avoid hard-coding the path to Ruby in the “shebang” line by using
#!/usr/bin/env ruby, which will search your path for ruby and then execute it.
9. Including http://www.ruby-doc.org and http://rubydoc.info
10. If you installed Ruby using rvm, there’s one additional step to get ri documentation available. At a
prompt, enter rvm docs generate.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 1. Getting Started • 12

For information on a particular method, give its name as a parameter:


$ ri GC::enable
---------------------------------------------------------------- GC::enable
GC.enable => true or false
---------------------------------------------------------------------------
Enables garbage collection, returning true if garbage collection was disabled.

GC.disable #=> false


GC.enable #=> true
GC.enable #=> false

If the method you give ri occurs in more than one class or module, ri will list the alternatives.
$ ri assoc
Implementation from Array
------------------------------------------------------------------------------
ary.assoc(obj) -> new_ary or nil
------------------------------------------------------------------------------
Searches through an array whose elements are also arrays comparing obj
with the first element of each contained array using obj.==.

Returns the first contained array that matches (that is, the first associated
array), or nil if no match is found.

See also Array#rassoc

s1 = [ "colors", "red", "blue", "green" ]


s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a = [ s1, s2, s3 ]
a.assoc("letters") #=> [ "letters", "a", "b", "c" ]
a.assoc("foo") #=> nil

(from ruby site)


Implementation from ENV
------------------------------------------------------------------------------
ENV.assoc(name) -> Array or nil
------------------------------------------------------------------------------
Returns an Array of the name and value of the environment variable with
name or nil if the name cannot be found.

(from ruby site)


Implementation from Hash
------------------------------------------------------------------------------
hash.assoc(obj) -> an_array or nil
------------------------------------------------------------------------------
Searches through the hash comparing obj with the key using ==.
Returns the key-value pair (two elements array) or nil if no match is
found. See Array#assoc.

h = {"colors" => ["red", "blue", "green"],


"letters" => ["a", "b", "c" ]}
h.assoc("letters") #=> ["letters", ["a", "b", "c"]]
h.assoc("foo") #=> nil

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Ruby Documentation: RDoc and ri • 13

For general help on using ri, type ri --help. In particular, you might want to experiment with
the --format option, which tells ri how to render decorated text (such as section headings). If
your terminal program supports ANSI escape sequences, using --format=ansi will generate a
nice, colorful display. Once you find a set of options you like, you can set them into the RI
environment variable. Using our shell (zsh), this would be done using the following:
$ export RI="--format ansi --width 70"

If a class or module isn’t yet documented in RDoc format, ask the friendly folks over at sug-
gestions@ruby-doc.org to consider adding it.

All this command-line hacking may seem a tad off-putting if you’re not a regular visitor to
the shell prompt. But, in reality, it isn’t that difficult, and the power you get from being able
to string together commands this way is often surprising. Stick with it, and you’ll be well
on your way to mastering both Ruby and your computer.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


CHAPTER 2

Ruby.new
Most books on programming languages look about the same. They start with chapters on
basic types: integers, strings, and so on. Then they look at expressions, before moving on to
if and while statements. Then, perhaps around Chapter 7 or 8, they’ll start mentioning classes.
We find that somewhat tedious.
Instead, when we designed this book, we had a grand plan (we were younger then). We
wanted to document the language from the top down, starting with classes and objects and
ending with the nitty-gritty syntax details. It seemed like a good idea at the time. After all,
most everything in Ruby is an object, so it made sense to talk about objects first.
Or so we thought.
Unfortunately, it turns out to be difficult to describe a language that way. If you haven’t
covered strings, if statements, assignments, and other details, it’s difficult to write examples
of classes. Throughout our top-down description, we kept coming across low-level details
we needed to cover so that the example code would make sense.
So, we came up with another grand plan (they don’t call us pragmatic for nothing). We’d
still describe Ruby starting at the top. But before we did that, we’d add a short chapter that
described all the common language features used in the examples along with the special
vocabulary used in Ruby, a kind of mini-tutorial to bootstrap us into the rest of the book.
And that mini-tutorial is this chapter.

2.1 Ruby Is an Object-Oriented Language


Let’s say it again. Ruby is a genuine object-oriented language. Everything you manipulate
is an object, and the results of those manipulations are themselves objects. However, many
languages make the same claim, and their users often have a different interpretation of what
object-oriented means and a different terminology for the concepts they employ.
So, before we get too far into the details, let’s briefly look at the terms and notation that we’ll
be using.
When you write object-oriented programs, you’re normally looking to model concepts from
the real world. During this modeling process you’ll discover categories of things that need
to be represented in code. In a jukebox, the concept of a “song” could be such a category. In
Ruby, you’d define a class to represent each of these entities. A class is a combination of state

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 2. Ruby.new • 16

(for example, the name of the song) and methods that use that state (perhaps a method to
play the song).
Once you have these classes, you’ll typically want to create a number of instances of each.
For the jukebox system containing a class called Song, you’d have separate instances for
popular hits such as “Ruby Tuesday,” “Enveloped in Python,” “String of Pearls,” “Small
Talk,” and so on. The word object is used interchangeably with class instance (and being lazy
typists, we’ll probably be using the word object more frequently).
In Ruby, these objects are created by calling a constructor, a special method associated with
a class. The standard constructor is called new.
song1 = Song.new("Ruby Tuesday")
song2 = Song.new("Enveloped in Python")
# and so on

These instances are both derived from the same class, but they have unique characteristics.
First, every object has a unique object identifier (abbreviated as object ID). Second, you can
define instance variables, variables with values that are unique to each instance. These instance
variables hold an object’s state. Each of our songs, for example, will probably have an instance
variable that holds the song title.
Within each class, you can define instance methods. Each method is a chunk of functionality
that may be called in the context of the class and (depending on accessibility constraints)
from outside the class. These instance methods in turn have access to the object’s instance
variables and hence to the object’s state. A Song class, for example, might define an instance
method called play. If a variable referenced a particular Song instance, you’d be able to call
that instance’s play method and play that song.
Methods are invoked by sending a message to an object. The message contains the method’s
1
name, along with any parameters the method may need. When an object receives a message,
it looks into its own class for a corresponding method. If found, that method is executed. If
the method isn’t found...well, we’ll get to that later.
This business of methods and messages may sound complicated, but in practice it is very
natural. Let’s look at some method calls. In this code, we’re using puts, a standard Ruby
method that writes its argument(s) to the console, adding a newline after each:
puts "gin joint".length
puts "Rick".index("c")
puts 42.even?
puts sam.play(song)
produces:
9
2
true
duh dum, da dum de dum ...

Each line shows a method being called as an argument to puts. The thing before the period
is called the receiver, and the name after the period is the method to be invoked. The first
example asks a string for its length; the second asks a different string to find the index of the
letter c. The third line asks the number 42 if it is even (the question mark is part of the method

1. This idea of expressing method calls in the form of messages comes from Smalltalk.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Some Basic Ruby • 17

name even?). Finally, we ask Sam to play us a song (assuming there’s an existing variable
called sam that references an appropriate object).
It’s worth noting here a major difference between Ruby and most other languages. In (say)
Java, you’d find the absolute value of some number by calling a separate function and
passing in that number. You could write this:
num = Math.abs(num) // Java code

In Ruby, the ability to determine an absolute value is built into numbers—they take care of
the details internally. You simply send the message abs to a number object and let it do the
work:
num = -1234 # => -1234
positive = num.abs # => 1234

The same applies to all Ruby objects. In C you’d write strlen(name), but in Ruby it would be
name.length, and so on. This is part of what we mean when we say that Ruby is a genuine
object-oriented language.

2.2 Some Basic Ruby


Not many people like to read heaps of boring syntax rules when they’re picking up a new
language, so we’re going to cheat. In this section, we’ll hit some of the highlights—the stuff
you’ll just need to know if you’re going to write Ruby programs. Later, in Chapter 22, The
Ruby Language, on page 297, we’ll go into all the gory details.
Let’s start with a simple Ruby program. We’ll write a method that returns a cheery, person-
alized greeting. We’ll then invoke that method a couple of times:
def say_goodnight(name)
result = "Good night, " + name
return result
end

# Time for bed...


puts say_goodnight("John-Boy")
puts say_goodnight("Mary-Ellen")
produces:
Good night, John-Boy
Good night, Mary-Ellen

As the example shows, Ruby syntax is clean. You don’t need semicolons at the ends of
statements as long as you put each statement on a separate line. Ruby comments start with
a # character and run to the end of the line. Code layout is pretty much up to you; indentation
is not significant (but using two-character indentation will make you friends in the commu-
nity if you plan on distributing your code).
Methods are defined with the keyword def, followed by the method name (in this case, the
name is say_goodnight) and the method’s parameters between parentheses. (In fact, the
parentheses are optional, but we like to use them.) Ruby doesn’t use braces to delimit the
bodies of compound statements and definitions. Instead, you simply finish the body with
the keyword end. Our method’s body is pretty simple. The first line concatenates the literal
string "Good night," and the parameter name and assigns the result to the local variable result.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 2. Ruby.new • 18

The next line returns that result to the caller. Note that we didn’t have to declare the variable
result; it sprang into existence when we assigned to it.

Having defined the method, we invoke it twice. In both cases, we pass the result to the
method puts, which simply outputs its argument followed by a newline (moving on to the
next line of output):
Good night, John-Boy
Good night, Mary-Ellen

The line
puts say_goodnight("John-Boy")

contains two method calls, one to the method say_goodnight and the other to the method puts.
Why does one call have its arguments in parentheses while the other doesn’t? In this case,
it’s purely a matter of taste. The following lines are equivalent:
puts say_goodnight("John-Boy")
puts(say_goodnight("John-Boy"))

However, life isn’t always that simple, and precedence rules can make it difficult to know
which argument goes with which method invocation, so we recommend using parentheses
in all but the simplest cases.
This example also shows some Ruby string objects. Ruby has many ways to create a string
object, but probably the most common is to use string literals, which are sequences of characters
between single or double quotation marks. The difference between the two forms is the
amount of processing Ruby does on the string while constructing the literal. In the single-
quoted case, Ruby does very little. With a few exceptions, what you enter in the string literal
becomes the string’s value.
In the double-quoted case, Ruby does more work. First, it looks for substitutions (sequences
that start with a backslash character) and replaces them with some binary value. The most
common of these is \n, which is replaced with a newline character. When a string containing
a newline is output, that newline becomes a line break:
puts "And good night,\nGrandma"
produces:
And good night,
Grandma

The second thing that Ruby does with double-quoted strings is expression interpolation.
Within the string, the sequence #{expression} is replaced by the value of expression. We could
use this to rewrite our previous method:
def say_goodnight(name)
result = "Good night, #{name}"
return result
end
puts say_goodnight('Pa')
produces:
Good night, Pa

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Some Basic Ruby • 19

When Ruby constructs this string object, it looks at the current value of name and substitutes
it into the string. Arbitrarily complex expressions are allowed in the #{...} construct. In the
following example, we invoke the capitalize method, defined for all strings, to output our
parameter with a leading uppercase letter:
def say_goodnight(name)
result = "Good night, #{name.capitalize}"
return result
end
puts say_goodnight('uncle')
produces:
Good night, Uncle

For more information on strings, as well as on the other Ruby standard types, see Chapter
6, Standard Types, on page 83.
Finally, we could simplify this method some more. The value returned by a Ruby method
is the value of the last expression evaluated, so we can get rid of the temporary variable and
the return statement altogether. This is idiomatic Ruby.
def say_goodnight(name)
"Good night, #{name.capitalize}"
end
puts say_goodnight('ma')
produces:
Good night, Ma

We promised that this section would be brief. We have just one more topic to cover: Ruby
names. For brevity, we’ll be using some terms (such as class variable) that we aren’t going to
define here. However, by talking about the rules now, you’ll be ahead of the game when we
actually come to discuss class variables and the like later.
Ruby uses a convention that may seem strange at first: the first characters of a name indicate
how the name is used. Local variables, method parameters, and method names should all
2
start with a lowercase letter or an underscore. Global variables are prefixed with a dollar
sign ($), and instance variables begin with an “at” sign (@). Class variables start with two
3
“at” signs (@@). Finally, class names, module names, and constants must start with an
uppercase letter. Samples of different names are given in Table 1, Example variable, class, and
constant names, on page 20.
Following this initial character, a name can be any combination of letters, digits, and
underscores (with the proviso that the character following an @ sign may not be a digit).
However, by convention, multiword instance variables are written with underscores between
the words, and multiword class names are written in MixedCase (with each word capitalized).
Method names may end with the characters ?, !, and =.

2. If your source files use non-ASCII characters (for example, because they’re written in UTF-8 encoding),
all non-ASCII characters are assumed to be lowercase letters.
3. Although we talk about global and class variables here for completeness, you’ll find they are rarely
used in Ruby programs. There’s a lot of evidence that global variables make programs harder to
maintain. Class variables are not as dangerous—it’s just that people tend not to use them much.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 2. Ruby.new • 20

Local Variable: name fish_and_chips x_axis thx1138 _x _26


Instance Variable: @name @point_1 @X @_ @plan9
Class Variable: @@total @@symtab @@N @@x_pos @@SINGLE
Global Variable: $debug $CUSTOMER $_ $plan9 $Global
Class Name: String ActiveRecord MyClass
Constant Name: FEET_PER_MILE DEBUG

Table 1—Example variable, class, and constant names

2.3 Arrays and Hashes


Ruby’s arrays and hashes are indexed collections. Both store collections of objects, accessible
using a key. With arrays, the key is an integer, whereas hashes support any object as a key.
Both arrays and hashes grow as needed to hold new elements. It’s more efficient to access
array elements, but hashes provide more flexibility. Any particular array or hash can hold
objects of differing types; you can have an array containing an integer, a string, and a floating-
point number, as we’ll see in a minute.
You can create and initialize a new array object using an array literal—a set of elements
between square brackets. Given an array object, you can access individual elements by
supplying an index between square brackets, as the next example shows. Note that Ruby
array indices start at zero.
a = [ 1, 'cat', 3.14 ] # array with three elements
puts "The first element is #{a[0]}"
# set the third element
a[2] = nil
puts "The array is now #{a.inspect}"
produces:
The first element is 1
The array is now [1, "cat", nil]

You may have noticed that we used the special value nil in this example. In many languages,
the concept of nil (or null) means “no object.” In Ruby, that’s not the case; nil is an object, just
like any other, that happens to represent nothing. Anyway, let’s get back to arrays and
hashes.
Sometimes creating arrays of words can be a pain, what with all the quotes and commas.
Fortunately, Ruby has a shortcut; %w does just what we want:
a = [ 'ant', 'bee', 'cat', 'dog', 'elk' ]
a[0] # => "ant"
a[3] # => "dog"
# this is the same:
a = %w{ ant bee cat dog elk }
a[0] # => "ant"
a[3] # => "dog"

Ruby hashes are similar to arrays. A hash literal uses braces rather than square brackets.
The literal must supply two objects for every entry: one for the key, the other for the value.
The key and value are normally separated by =>.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Symbols • 21

For example, you could use a hash to map musical instruments to their orchestral sections.
inst_section = {
'cello' => 'string',
'clarinet' => 'woodwind',
'drum' => 'percussion',
'oboe' => 'woodwind',
'trumpet' => 'brass',
'violin' => 'string'
}

The thing to the left of the => is the key, and the thing to the right is the corresponding value.
Keys in a particular hash must be unique; you can’t have two entries for “drum.” The keys
and values in a hash can be arbitrary objects. You can have hashes where the values are
arrays, other hashes, and so on.
Hashes are indexed using the same square bracket notation as arrays. In this code, we’ll use
the p method to write the values to the console. This works like puts but displays values such
as nil explicitly.
p inst_section['oboe']
p inst_section['cello']
p inst_section['bassoon']
produces:
"woodwind"
"string"
nil

As the previous example shows, a hash by default returns nil when indexed by a key it doesn’t
contain. Normally this is convenient, because nil means false when used in conditional
expressions. Sometimes you’ll want to change this default. For example, if you’re using a
hash to count the number of times each different word occurs in a file, it’s convenient to
have the default value be zero. Then you can use the word as the key and simply increment
the corresponding hash value without worrying about whether you’ve seen that word before.
This is easily done by specifying a default value when you create a new, empty hash. (Have
a look at the full source for the word frequency counter on page 49.)
histogram = Hash.new(0) # The default value is zero
histogram['ruby'] # => 0
histogram['ruby'] = histogram['ruby'] + 1
histogram['ruby'] # => 1

Array and hash objects have many useful methods; see the discussion on page 45, as well
as the reference sections for arrays on page 421 and for hashes on page 521.

2.4 Symbols
Often, when programming, you need to create a name for something significant. For example,
you might want to refer to the compass points by name, so you’d write this:
NORTH = 1
EAST = 2
SOUTH = 3
WEST = 4

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 2. Ruby.new • 22

Then, in the rest of your code, you could use the constants instead of the numbers:
walk(NORTH)
look(EAST)

Most of the time, the actual numeric values of these constants are irrelevant (as long as they
are unique). All you want to do is differentiate the four directions.
Ruby offers a cleaner alternative. Symbols are simply constant names that you don’t have to
predeclare and that are guaranteed to be unique. A symbol literal starts with a colon and is
normally followed by some kind of name:
walk(:north)
look(:east)

There’s no need to assign some kind of value to a symbol—Ruby takes care of that for you.
Ruby also guarantees that no matter where it appears in your program, a particular symbol
will have the same value. That is, you can write the following:
def walk(direction)
if direction == :north
# ...
end
end

Symbols are frequently used as keys in hashes. We could write our previous example as
this:
inst_section = {
:cello => 'string',
:clarinet => 'woodwind',
:drum => 'percussion',
:oboe => 'woodwind',
:trumpet => 'brass',
:violin => 'string'
}
inst_section[:oboe] # => "woodwind"
inst_section[:cello] # => "string"
# Note that strings aren't the same as symbols...
inst_section['cello'] # => nil

In fact, symbols are so frequently used as hash keys that Ruby has a shortcut syntax: you
can use name: value pairs to create a hash if the keys are symbols:
inst_section = {
cello: 'string',
clarinet: 'woodwind',
drum: 'percussion',
oboe: 'woodwind',
trumpet: 'brass',
violin: 'string'
}
puts "An oboe is a #{inst_section[:oboe]} instrument"
produces:
An oboe is a woodwind instrument

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Control Structures • 23

2.5 Control Structures


Ruby has all the usual control structures, such as if statements and while loops. Java, C, and
Perl programmers may well get caught by the lack of braces around the bodies of these
statements. Instead, Ruby uses the keyword end to signify the end of a body of all the control
structures:
today = Time.now

if today.saturday?
puts "Do chores around the house"
elsif today.sunday?
puts "Relax"
else
puts "Go to work"
end
produces:
Go to work

Similarly, while statements are terminated with end:


num_pallets = 0
weight = 0
while weight < 100 and num_pallets <= 5
pallet = next_pallet()
weight += pallet.weight
num_pallets += 1
end

Most statements in Ruby return a value, which means you can use them as conditions. For
example, the kernel method gets returns the next line from the standard input stream or nil
when the end of the file is reached. Because Ruby treats nil as a false value in conditions, you
could write the following to process the lines in a file:
while line = gets
puts line.downcase
end

Here, the assignment statement sets the variable line to either the next line of text or nil, and
then the while statement tests the value of the assignment, terminating the loop when it is nil.
Ruby statement modifiers are a useful shortcut if the body of an if or while statement is just a
single expression. Simply write the expression, followed by if or while and the condition. For
example, here’s a simple if statement:
if radiation > 3000
puts "Danger, Will Robinson"
end

Here it is again, rewritten using a statement modifier:


puts "Danger, Will Robinson" if radiation > 3000

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 2. Ruby.new • 24

Similarly, this while loop:


square = 4
while square < 1000
square = square*square
end

becomes this more concise version:


square = 4
square = square*square while square < 1000

These statement modifiers should seem familiar to Perl programmers.

2.6 Regular Expressions


Most of Ruby’s built-in types will be familiar to all programmers. A majority of languages
have strings, integers, floats, arrays, and so on. However, regular expression support is
typically built into only scripting languages, such as Ruby, Perl, and awk. This is a shame,
because regular expressions, although cryptic, are a powerful tool for working with text.
And having them built in, rather than tacked on through a library interface, makes a big
difference.
Entire books have been written about regular expressions (for example, Mastering Regular
Expressions [Fri97]), so we won’t try to cover everything in this short section. Instead, we’ll
look at just a few examples of regular expressions in action. You’ll find full coverage of reg-
ular expressions in Chapter 7, Regular Expressions, on page 93.
A regular expression is simply a way of specifying a pattern of characters to be matched in
a string. In Ruby, you typically create a regular expression by writing a pattern between
slash characters (/pattern/). And, Ruby being Ruby, regular expressions are objects and can
be manipulated as such.
For example, you could write a pattern that matches a string containing the text Perl or the
text Python using the following regular expression:
/Perl|Python/

The forward slashes delimit the pattern, which consists of the two things we’re matching,
separated by a pipe character (|). This pipe character means “either the thing on the right or
the thing on the left,” in this case either Perl or Python. You can use parentheses within pat-
terns, just as you can in arithmetic expressions, so you could also have written this pattern
like this:
/P(erl|ython)/

You can also specify repetition within patterns. /ab+c/ matches a string containing an a followed
by one or more b’s, followed by a c. Change the plus to an asterisk, and /ab*c/ creates a regular
expression that matches one a, zero or more b’s, and one c.
You can also match one of a group of characters within a pattern. Some common examples
are character classes such as \s, which matches a whitespace character (space, tab, newline,
and so on); \d, which matches any digit; and \w, which matches any character that may appear
in a typical word. A dot (.) matches (almost) any character. A table of these character classes
appears in Table 2, Character class abbreviations, on page 101.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Blocks and Iterators • 25

We can put all this together to produce some useful regular expressions:
/\d\d:\d\d:\d\d/ # a time such as 12:34:56
/Perl.*Python/ # Perl, zero or more other chars, then Python
/Perl Python/ # Perl, a space, and Python
/Perl *Python/ # Perl, zero or more spaces, and Python
/Perl +Python/ # Perl, one or more spaces, and Python
/Perl\s+Python/ # Perl, whitespace characters, then Python
/Ruby (Perl|Python)/ # Ruby, a space, and either Perl or Python

Once you have created a pattern, it seems a shame not to use it. The match operator =~ can
be used to match a string against a regular expression. If the pattern is found in the string,
=~ returns its starting position; otherwise, it returns nil. This means you can use regular
expressions as the condition in if and while statements. For example, the following code
fragment writes a message if a string contains the text Perl or Python:
line = gets
if line =~ /Perl|Python/
puts "Scripting language mentioned: #{line}"
end

The part of a string matched by a regular expression can be replaced with different text using
one of Ruby’s substitution methods:
line = gets
newline = line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'
newerline = newline.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'

You can replace every occurrence of Perl and Python with Ruby using this:
line = gets
newline = line.gsub(/Perl|Python/, 'Ruby')

We’ll have a lot more to say about regular expressions as we go through the book.

2.7 Blocks and Iterators


This section briefly describes one of Ruby’s particular strengths. We’re about to look at code
blocks, which are chunks of code you can associate with method invocations, almost as if
they were parameters. This is an incredibly powerful feature. One of our reviewers comment-
ed at this point: “This is pretty interesting and important, so if you weren’t paying attention
before, you should probably start now.” We’d have to agree.
You can use code blocks to implement callbacks (but they’re simpler than Java’s anonymous
inner classes), to pass around chunks of code (but they’re more flexible than C’s function
pointers), and to implement iterators.
Code blocks are just chunks of code between braces or between do and end. This is a code
block:
{ puts "Hello" }

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Chapter 2. Ruby.new • 26

This is also a code block:


do
club.enroll(person)
person.socialize
end

Why are there two kinds of delimiter? It’s partly because sometimes one feels more natural
to write than another. It’s partly too because they have different precedences: the braces
bind more tightly than the do/end pairs. In this book, we try to follow what is becoming a
Ruby standard and use braces for single-line blocks and do/end for multiline blocks.
All you can do with a block is associate it with a call to a method. You do this by putting the
start of the block at the end of the source line containing the method call.
For example, in the following code, the block containing puts "Hi" is associated with the call
to the method greet (which we don’t show):
greet { puts "Hi" }

If the method has parameters, they appear before the block:


verbose_greet("Dave", "loyal customer") { puts "Hi" }

A method can then invoke an associated block one or more times using the Ruby yield
statement. You can think of yield as being something like a method call that invokes the block
associated with the call to the method containing the yield.
The following example shows this in action. We define a method that calls yield twice. We
then call this method, putting a block on the same line, after the call (and after any arguments
4
to the method).
def call_block
puts "Start of method"
yield
yield
puts "End of method"
end

call_block { puts "In the block" }


produces:
Start of method
In the block
In the block
End of method

The code in the block (puts "In the block") is executed twice, once for each call to yield.
You can provide arguments to the call to yield, and they will be passed to the block. Within
the block, you list the names of the parameters to receive these arguments between vertical
bars (|params...|). The following example shows a method calling its associated block twice,
passing the block two arguments each time:

4. Some people like to think of the association of a block with a method as a kind of argument passing.
This works on one level, but it isn’t really the whole story. You may be better off thinking of the block
and the method as coroutines, which transfer control back and forth between themselves.

Download from Wow! eBook <www.wowebook.com> report erratum • discuss


Exploring the Variety of Random
Documents with Different Content
THE
FERN OWL,
OR
NIGHT JAR.

This is a very harmless bird, about the size of the small Sparrow-
Hawk, of a dark colour, and with a large mouth. They never go out
till the evening, and then catch beetles and other insects for their
sustenance.
THE
RAVEN.

This is the largest bird that feeds on carrion, and is of a fine shining
colour; in some places it is very serviceable, in eating up the stinking
flesh or carcases of dead beasts and other carrion, but in many other
places very mischievous, and does a great deal of harm. I having been
allowed as much per head for killing them as I had for kites and
hawks, as they are equally pernicious in killing and devouring young
rabbits, ducklings and chickens.
I know of no better way to catch them, where they become
troublesome, than to set two traps for them, in the same manner as
you do for the buzzard, [see plate VI. fig. 1.] and put a rat between
them for a bait, but when you have taken one or two, you must move
your traps to another place, or the others will prove too shy to be
caught; for as soon as one is taken, great numbers will keep round
him, and seeing him fast, will grow suspicious of some danger, and
not come near the place any more; but by observing the above
method, in moving the traps, I have caught great numbers of them in
a day, though it is attended with some labour and trouble.
I have often caught the London Ravens near twenty miles from
home, in warrens, where they will sometimes come after the young
Rabbits; by the London Ravens I mean those that generally frequent
the outskirts of the metropolis, and live upon the filth lying there,
grubbing up the dirt in order to get at their food, from whence the
tops of their wings become of a nasty, dusky brown colour,
occasioned by their wallowing in the dirt, by which means they are
easily distinguishable from the country Ravens, which are as black as
jet, according to the old saying, As black as a Raven.
I have seen some of these Ravens sit upon a lamb, that has been
dropped weak, not being able to run, when they have got to his head
and picked out the creature’s eyes while yet alive. Another remark I
shall make, which is to point out the difference between the manner
of birds of the hawk kind carrying their prey, and those of the carrion
kind. Now it is observable that buzzards, kites, hawks and owls,
constantly carry their prey in their claws, whereas Ravens, carrion-
crows and magpies carry their food in their beaks.
THE
CARRION
CROW.

This bird is well known, and in country places will do prodigious


mischief, by destroying young rabbits, chickens and ducks, and
likewise in sucking eggs, which the hens and ducks lay in the back
yards or in the hedges: these the Crows will break and eat as greedily
as any other vermin whatever. Now if you find they have any haunts
about your house, get a steel trap, of the same kind as you use for
other winged vermin; set it in the ground, quite level with the
surface, and cover it with moss; then take a little piece of bush or
some fern, stick some of it down, by one jaw quite low, and bring it
round to the other jaw, [see plate VI. fig. 1.] put the bait, whether it
be an egg, or rat, a piece of rabbit, or the guts of the same, or any
thing else of this sort, in the back part, on the tail of the trap; and
when you have put the little fence, before described all around, as a
guide for him, he must of necessity go over the trap for the bait, and
be caught; but I have been plagued with these as much as I have been
with the Ravens, by being obliged to move the trap after every Crow I
had taken; but by observing when one is caught, which you may
easily hear, for they then make a great noise and keep flying round
their imprisoned brother, almost close to the ground, you may then
probably get a shoot, and kill some of them; but sometimes I have
known them so shy that I could not get them to the trap at any rate.
In this case you must observe the places where they most frequent,
and take a cat, or a ferret, and tie it to a stake; then take a gun, and
hide yourself, when the first Crow that sees the cat or ferret will
make a terrible screaming noise, and bring many more, who scream
and hover about till you have a fair shoot. In this manner I have had,
sometimes, three or four shoots before they dispersed, and killed
several of them; for when they see any kind of animal they are not
used to, in the day-time, it greatly attracts their attention, and they
wonder at it, as the small birds do at the sight of an owl by day-light;
and this is the best way to get at the shy ones. I have seen the Crows
pick out the eyes of a weak lamb, while alive, in the same manner as
the ravens will.
THE
MAGPYE.

This is a very mischievous bird, doing great damage in warrens, and


much of the same nature as the crow, preying on all kinds of flesh
and carrion, like that animal. They are extremely pernicious about
farm-yards and houses, killing and devouring young ducks and
chickens, and likewise in sucking and destroying eggs in great
numbers, about farm-houses, where the hens lay them by the sides of
the rickyards and under the hedges. When you find they become
troublesome in the above instances, set your trap (where you observe
them to come) in the same manner as you do for the crow; bait it
with a rat, which is as good a bait as any, or with an egg; or if they
have killed any young ducks or chickens, and have not devoured
them, at that place, where you find them, set your trap, and bait it
with the dead duckling or chicken, and you need not fear catching
them: but be careful to observe the following rule, which is, as soon
as one of the Magpyes is trapped, to take it out as soon as possible, in
order to set your trap again. You may easily discover this event, for as
soon as one is taken in the trap, it makes a screaming noise, which
brings great numbers of these vermin together, who come hovering
and flying over their captive brother, which will give you a fair
opportunity of shooting among them and destroying many. This
method I have often put into execution, and it has been attended
with very good success.

FINIS.
TRANSCRIBER’S NOTES
Typos fixed; non-standard spelling and dialect
retained.
Used numbers for footnotes.
The original did not include Plate II.
*** END OF THE PROJECT GUTENBERG EBOOK THE UNIVERSAL
DIRECTORY FOR TAKING ALIVE AND DESTROYING RATS, ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like