100% found this document useful (2 votes)
26 views

Download ebooks file Programming Ruby 1 9 3rd Edition Dave Thomas all chapters

Ruby

Uploaded by

laisycolver
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
26 views

Download ebooks file Programming Ruby 1 9 3rd Edition Dave Thomas all chapters

Ruby

Uploaded by

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

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Programming Ruby 1 9 3rd Edition Dave Thomas

_____ Click the link below to download _____


https://ebookgate.com/product/programming-ruby-1-9-3rd-
edition-dave-thomas/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Programming Ruby The Pragmatic Programmers Guide 2 nd


edition Dave Thomas

https://ebookgate.com/product/programming-ruby-the-pragmatic-
programmers-guide-2-nd-edition-dave-thomas/

ebookgate.com

The Well Grounded Rubyist Covering Ruby 1 9 1st Edition


David A. Black

https://ebookgate.com/product/the-well-grounded-rubyist-covering-
ruby-1-9-1st-edition-david-a-black/

ebookgate.com

The Ruby Programming Language 1st Edition David Flanagan

https://ebookgate.com/product/the-ruby-programming-language-1st-
edition-david-flanagan/

ebookgate.com

Programming Elixir 1 3 Functional Concurrent Pragmatic Fun


1st Edition David Thomas

https://ebookgate.com/product/programming-elixir-1-3-functional-
concurrent-pragmatic-fun-1st-edition-david-thomas/

ebookgate.com
Programming Visual Basic NET 1st ed Edition Dave
Grundgeiger

https://ebookgate.com/product/programming-visual-basic-net-1st-ed-
edition-dave-grundgeiger/

ebookgate.com

Programming Cocoa with Ruby Create Compelling Mac Apps


Using RubyCocoa The Facets of Ruby Series 1st Edition
Brian Marick
https://ebookgate.com/product/programming-cocoa-with-ruby-create-
compelling-mac-apps-using-rubycocoa-the-facets-of-ruby-series-1st-
edition-brian-marick/
ebookgate.com

IOS 9 Swift programming cookbook First Edition


Nahavandipoor

https://ebookgate.com/product/ios-9-swift-programming-cookbook-first-
edition-nahavandipoor/

ebookgate.com

Python 2 1 Bible 1st Edition Dave Brueck

https://ebookgate.com/product/python-2-1-bible-1st-edition-dave-
brueck/

ebookgate.com

Urban Geography 3rd Edition Dave H. Kaplan

https://ebookgate.com/product/urban-geography-3rd-edition-dave-h-
kaplan/

ebookgate.com
Programming Ruby 1.9
The Pragmatic Programmers’ Guide

Dave Thomas
with Chad Fowler
and Andy Hunt

The Pragmatic Bookshelf


Raleigh, North Carolina Dallas, Texas
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.

Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for
errors or omissions or for damages that may result from the use of information (including program listings) contained
herein.

This book is a heavily revised version of the book Programming Ruby, originally published by Addison Wesley.
This book is printed with their permission.

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://www.pragmaticprogrammer.com

Copyright © 2009 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be repro-
duced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopy-
ing, recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.

ISBN: 1-934356-08-5
ISBN-13: 978-1-934356-08-1

Text printed on acid-free paper.


Contents
F OREWORD 16
P REFACE 17
ROAD M AP 22

PART I—FACETS OF RUBY

1 G ETTING S TARTED 25
The Command Prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Installing Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Running Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Ruby Documentation: RDoc and ri . . . . . . . . . . . . . . . . . . . . . . . . 32

2 RUBY. NEW 35
Ruby Is an Object-Oriented Language . . . . . . . . . . . . . . . . . . . . . . 35
Some Basic Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Arrays and Hashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Blocks and Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Reading and ’Riting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Command-Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Onward and Upward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

3 C LASSES , O BJECTS , AND VARIABLES 50


Objects and Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Classes Working with Other Classes . . . . . . . . . . . . . . . . . . . . . . . 58
Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

4
CONTENTS 5

4 C ONTAINERS , B LOCKS , AND I TERATORS 67


Blocks and Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Containers Everywhere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

5 S HARING F UNCTIONALITY: I NHERITANCE , M ODULES , AND M IXINS 91


Inheritance and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Iterators and the Enumerable Module . . . . . . . . . . . . . . . . . . . . . . . 100
Composing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Inheritance, Mixins, and Design . . . . . . . . . . . . . . . . . . . . . . . . . 104

6 S TANDARD T YPES 106


Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

7 R EGULAR E XPRESSIONS 117


What Regular Expressions Let You Do . . . . . . . . . . . . . . . . . . . . . . 117
Ruby’s Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Digging Deeper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Pattern-Based Substitution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Advanced Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 130

8 M ORE A BOUT M ETHODS 137


Defining a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Calling a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

9 E XPRESSIONS 146
Operator Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Miscellaneous Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Conditional Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Case Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Variable Scope, Loops, and Blocks . . . . . . . . . . . . . . . . . . . . . . . . 165

10 E XCEPTIONS , C ATCH , AND T HROW 167


The Exception Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Raising Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Catch and Throw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

11 BASIC I NPUT AND O UTPUT 176


What Is an IO Object? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Opening and Closing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Reading and Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Talking to Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
CONTENTS 6

12 F IBERS , T HREADS , AND P ROCESSES 184


Fibers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Controlling the Thread Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . 190
Mutual Exclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Running Multiple Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

13 U NIT T ESTING 198


The Testing Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Structuring Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Organizing and Running Tests . . . . . . . . . . . . . . . . . . . . . . . . . . 206
RSpec and Shoulda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

14 W HEN T ROUBLE S TRIKES 220


Ruby Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Interactive Ruby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Editor Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
But It Doesn’t Work! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
But It’s Too Slow! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

PART II—RUBY IN I TS S ETTING

15 RUBY AND I TS W ORLD 233


Command-Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Program Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Where Ruby Finds Its Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . 238
RubyGems Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
The Rake Build Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Build Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

16 NAMESPACES , S OURCE F ILES , AND D ISTRIBUTION 249


Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Organizing Your Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Distributing and Installing Your Code . . . . . . . . . . . . . . . . . . . . . . 258

17 C HARACTER E NCODING 264


Encodings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
Transcoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Input and Output Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Default External Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Encoding Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Default Internal Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Fun with Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
CONTENTS 7

18 I NTERACTIVE RUBY S HELL 278


Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288

19 D OCUMENTING RUBY 290


Adding RDoc to Ruby Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Adding RDoc to C Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Running RDoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299

20 RUBY AND THE W EB 304


Writing CGI Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Choice of Web Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

21 RUBY AND M ICROSOFT W INDOWS 316


Getting Ruby for Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Running Ruby Under Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Win32API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Windows Automation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318

PART III—RUBY C RYSTALLIZED

22 T HE RUBY L ANGUAGE 325


Source File Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Source Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
The Basic Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Variables and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Method Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Invoking a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Aliasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Module Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Blocks, Closures, and Proc Objects . . . . . . . . . . . . . . . . . . . . . . . . 363
Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Catch and Throw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
CONTENTS 8

23 D UCK T YPING 370


Classes Aren’t Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Coding like a Duck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Standard Protocols and Coercions . . . . . . . . . . . . . . . . . . . . . . . . 376
Walk the Walk, Talk the Talk . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

24 M ETAPROGRAMMING 384
Objects and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Singletons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Inheritance and Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Modules and Mixins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
Metaprogramming Class-Level Macros . . . . . . . . . . . . . . . . . . . . . . 397
Two Other Forms of Class Definition . . . . . . . . . . . . . . . . . . . . . . . 402
instance_eval and class_eval . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Hook Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
One Last Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Top-Level Execution Environment . . . . . . . . . . . . . . . . . . . . . . . . 417
The Turtle Graphics Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

25 R EFLECTION , O BJECT S PACE , AND D ISTRIBUTED RUBY 420


Looking at Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Looking at Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
Calling Methods Dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . 423
System Hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Tracing Your Program’s Execution . . . . . . . . . . . . . . . . . . . . . . . . 427
Behind the Curtain: The Ruby VM . . . . . . . . . . . . . . . . . . . . . . . . 430
Marshaling and Distributed Ruby . . . . . . . . . . . . . . . . . . . . . . . . . 431
Compile Time? Runtime? Anytime! . . . . . . . . . . . . . . . . . . . . . . . 435

26 L OCKING RUBY IN THE S AFE 436


Safe Levels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
Tainted Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
Trusted Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438

PART IV—RUBY L IBRARY R EFERENCE

27 B UILT- IN C LASSES AND M ODULES 442


Alphabetical Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
BasicObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
Bignum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Comparable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
CONTENTS 9

Dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
Enumerable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Enumerator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
Errno . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
FalseClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
Fiber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
File::Stat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
FileTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
Fixnum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
Float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
GC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
Hash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Marshal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
MatchData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Mutex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
NilClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
Numeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
ObjectSpace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Proc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
Process::GID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
Process::Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
Process::Sys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Process::UID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
Rational . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
Regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
Struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
Struct::Tms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
Symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
ThreadGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
TrueClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
CONTENTS 10

UnboundMethod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724

28 S TANDARD L IBRARY 726


Library Changes in Ruby 1.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
Abbrev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
Base64 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 730
Benchmark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
BigDecimal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
CGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
CGI::Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
CMath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
Complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
Continuation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738
CSV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Curses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
Date/DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
DBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 743
Delegator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
Digest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
DL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746
dRuby . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
English . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
erb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
Etc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
expect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
Fcntl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
Fiber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
FileUtils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Forwardable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
GDBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
GetoptLong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
GServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
Iconv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
IO/Wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
IPAddr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763
irb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764
json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
Logger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
mathn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
MiniTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
Mutex_m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
Net::FTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
Net::HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
Net::IMAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
CONTENTS 11

Net::POP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
Net::SMTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
Net::Telnet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
NKF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
Observable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
open-uri . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
Open3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
OptionParser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
OpenStruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
Pathname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
PP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
PrettyPrint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
prime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
Profiler_ _ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
PStore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 794
PTY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
Rational . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
Readline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
Resolv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
REXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
Rinda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801
Ripper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
RSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
Scanf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
SDBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
SecureRandom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
Shellwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
Singleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
StringIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 812
StringScanner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
Syslog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
Tempfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
Test::Unit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816
thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
ThreadsWait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
Tk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
tmpdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
Tracer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
TSort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
un . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825
CONTENTS 12

URI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
WeakRef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
WEBrick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 828
WIN32OLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
XMLRPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830
YAML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
Zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832

29 E XTENDING RUBY 833


Your First Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
Ruby Objects in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836
The Threading Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
The Jukebox Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 852
Ruby Type System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
Creating an Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
Embedding a Ruby Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . 860
Bridging Ruby to Other Environments . . . . . . . . . . . . . . . . . . . . . . 864
Ruby C Language API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865
MKMF Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
mkmf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874

PART V—A PPENDIXES

A S OCKET L IBRARY 878


BasicSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879
Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
IPSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885
TCPSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 886
SOCKSSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
TCPServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
UDPSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889
UNIXSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
UNIXServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892

B S UPPORT 893
Websites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 893
Usenet Newsgroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
Mailing Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
Bug Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
CONTENTS 13

C B IBLIOGRAPHY 896

I NDEX 897
List of Tables
2.1 Example Variable and Class Names . . . . . . . . . . . . . . . . . . . . . . 41
7.1 Character Class Abbreviations . . . . . . . . . . . . . . . . . . . . . . . . . 125
7.2 Posix Character Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
7.3 Unicode Character Properties . . . . . . . . . . . . . . . . . . . . . . . . . 126
9.1 Common Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . 156
14.1 Debugger Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
15.1 Environment Variables Used by Ruby . . . . . . . . . . . . . . . . . . . . . 238
15.2 Version Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
18.1 irb Command-Line Options . . . . . . . . . . . . . . . . . . . . . . . . . . 279
20.1 Command-Line Options for erb . . . . . . . . . . . . . . . . . . . . . . . . 312
22.1 General Delimited Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
22.2 Substitutions in Double-Quoted Strings . . . . . . . . . . . . . . . . . . . . 329
22.3 Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
22.4 Ruby Operators (High to Low Precedence) . . . . . . . . . . . . . . . . . . 345
24.1 Ruby Hook Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
26.1 Definition of the Safe Levels . . . . . . . . . . . . . . . . . . . . . . . . . . 440
27.1 Class Array: pack directives . . . . . . . . . . . . . . . . . . . . . . . . . . 456
27.2 Encoding Names and Class Names . . . . . . . . . . . . . . . . . . . . . . . 484
27.3 Class File: Match-Mode Constants . . . . . . . . . . . . . . . . . . . . . . . 510
27.4 Class File: Path Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
27.5 Class File: Open-Mode Constants . . . . . . . . . . . . . . . . . . . . . . . 514
27.6 Class File: Lock-Mode Constants . . . . . . . . . . . . . . . . . . . . . . . 518
27.7 Class IO: Mode Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
27.8 Module Kernel: Options to Spawn and System . . . . . . . . . . . . . . . . 580
27.9 Module Kernel: sprintf Flag Characters . . . . . . . . . . . . . . . . . . . 581
27.10 Module Kernel: sprintf Field Types . . . . . . . . . . . . . . . . . . . . . 581
27.11 Module Kernel: File Tests with a Single Argument . . . . . . . . . . . . . . 582
27.12 Module Kernel: File Tests with Two Arguments . . . . . . . . . . . . . . . . 582
27.13 Class Numeric: Methods and Subclasses . . . . . . . . . . . . . . . . . . . . 618
27.14 Class Numeric: divmod, modulo, and remainder . . . . . . . . . . . . . . . 619
27.15 Class String: Options to Encode . . . . . . . . . . . . . . . . . . . . . . . . 680
27.16 Class String: Backslash Sequences in Substitution Strings . . . . . . . . . . 682
27.17 Class String: unpack Directives . . . . . . . . . . . . . . . . . . . . . . . . 694
27.18 Class Time: strftime Directives . . . . . . . . . . . . . . . . . . . . . . . . 720
28.1 Class ERB: Inline Directives . . . . . . . . . . . . . . . . . . . . . . . . . . 750
28.2 Class OptionParser: Option Definitions . . . . . . . . . . . . . . . . . . . . 786
29.1 C/Ruby Data Type Conversion Functions and Macros . . . . . . . . . . . . 838
29.2 Object Accessor Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841

14
List of Figures
3.1 Variables Hold Object References . . . . . . . . . . . . . . . . . . . . . . . 66
4.1 How Arrays Are Indexed . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
10.1 Ruby Exception Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
13.1 Testing Framework Assertions . . . . . . . . . . . . . . . . . . . . . . . . . 218
13.2 Additional Test::Unit Assertions . . . . . . . . . . . . . . . . . . . . . . . . 219
14.1 Sample irb Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
14.2 Determining Method Calling Costs Using Benchmark . . . . . . . . . . . . 228
15.1 Installed Documentation for Builder . . . . . . . . . . . . . . . . . . . . . . 242
17.1 Encodings and Their Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . 266
19.1 Browse RDoc Output for Class Counter . . . . . . . . . . . . . . . . . . . . 291
19.2 Browse RDoc Output When Source Has Comments . . . . . . . . . . . . . 292
19.3 Using ri to Read Documentation . . . . . . . . . . . . . . . . . . . . . . . . 293
19.4 Documentation for Class Proc Generated by RDoc/ri . . . . . . . . . . . . . 294
19.5 Ruby Source File Documented with RDoc . . . . . . . . . . . . . . . . . . . 302
19.6 C Source File Documented with RDoc . . . . . . . . . . . . . . . . . . . . . 303
20.1 Sample CGI Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
22.1 State Transitions for Boolean Range . . . . . . . . . . . . . . . . . . . . . . 348
24.1 Object Model for a Basic Class . . . . . . . . . . . . . . . . . . . . . . . . . 387
24.2 Object Model for a Singleton Class . . . . . . . . . . . . . . . . . . . . . . 389
24.3 Basic Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
24.4 Class with So-Called Class Methods . . . . . . . . . . . . . . . . . . . . . . 392
24.5 How Modules Are Included . . . . . . . . . . . . . . . . . . . . . . . . . . 396
27.1 Standard Exception Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . 502
27.2 Method#arity in Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
29.1 Wrapping Objects Around C Data Types . . . . . . . . . . . . . . . . . . . 846
29.2 Building an Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856

15
Foreword
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 out 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. Uncountable 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, a.k.a. “Matz”

Japan, February 2009

16
Preface
This book is a new version of the PickAxe, as Programming Ruby is known to Ruby pro-
grammers. It is a tutorial and reference for the version 1.9 of Ruby programming language.
Ruby 1.9 is 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.
Given a choice between showing the 1.8 version of some Ruby construct and the 1.9 ver-
sion, this book shows the new way. If you’re planning to use Ruby 1.8 and not Ruby 1.9,
then I’d recommend putting this book down and instead looking at the second edition of
Programming Ruby.1
But, before you run off, I’d also like you to stop for a second and consider switching to
Ruby 1.9. As a language, and as a programming environment, it really is a step up from
previous versions of Ruby. It runs faster, it is more expressive, and it enables even more
programming paradigms. Most frameworks (including Ruby on Rails) are now compatible
with Ruby 1.9. And some Ruby implementations (such as MacRuby—a version of Ruby
that is integrated into the Objective C runtime on the Mac) run only 1.9 code.

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. Almost eight years later, Ruby is still our 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.

1. http://pragprog.com/titles/ruby

17
P REFACE 18

In those eight 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 stan-
dard 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 framework,
Ruby on Rails, with others waiting in the wings.

Ruby Versions
This version of the PickAxe documents Ruby 1.9.2
Exactly what version of Ruby did I use to write this book? Let’s ask Ruby:
% ruby -v
ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-darwin9.6.0]

This illustrates an important point. Most of the code samples you see in this book are actu-
ally 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 back into the book.

Changes in the Book


Throughout the book I’ve tried to mark changes between 1.8 and 1.9 using a small symbol
1.9 in the margin, like the one here. 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.

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 B).
And I’d certainly appreciate hearing from you. Comments, suggestions, errors in the text,
and problems in the examples are all welcome. E-mail us at
rubybook@pragprog.com

2. 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.
P REFACE 19

If you tell us about errors in the book, I’ll add them to the errata list at
http://www.pragprog.com/titles/ruby3/errata.html

You’ll find links to the source code for almost all the book’s example code at
http://www.pragprog.com/titles/ruby3

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 since then. 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
contributed 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.
Getting this book into production has also been a challenge. Many thanks to Kim Wimpsett
for doing an amazing job on the copy edit, Steve Peter for finding ways to lay out all those
awkward pages full of code, and Janet Furlow for keeping us all on track.
Finally, I’m still deeply indebted to Yukihiro “Matz” Matsumoto, the creator of Ruby.
Throughout this period of growth and change, he has remained helpful, cheery, and ded-
icated to polishing this gem of a language. The friendly and open spirit of the Ruby com-
munity is a direct reflection of the person at its center.
Thank you all. Domo arigato gozaimasu.
Dave Thomas
T HE P RAGMATIC P ROGRAMMERS
http://www.pragprog.com
P REFACE 20

Notation Conventions
Throughout this book, we use the following typographic notations.
Literal code examples are shown using a typewriter-like font:
Download samples/preface_2.rb

class SampleCode
def run
#...
end
end

Within the text, Fred#do_something is a reference to an instance method (in this case
do_something) of class Fred, Fred.new3 is a class method, and Fred::EOF is a class con-
stant. 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.
The 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. For example:
Download samples/preface_3.rb

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, in which case we’ll
show them:
Download samples/preface_4.rb

a = 1 # => 1
b = 2 # => 2
a + b # => 3

3. 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.
P REFACE 21

If the program produces more complex output, we show it below the program code:
Download samples/preface_5.rb

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 Roman font, and parameters you
supply are shown in an italic font. Optional elements are shown in large square brackets.
ruby [ flags ... ] [ progname ] [ arguments ... ]
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 environ-
ment (including wonderful things such as native API calls, COM integration, and Windows
Automation). We’ll also touch on using Ruby to access the ’net.
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, metaprogram-
ming, 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,250 methods in
more than 54 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 (96 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 environ-
ment, you may want to investigate some of the more advanced topics in Part III.

22
P REFACE 23

If you’re already comfortable with Perl, Python, Java, or Smalltalk, then we suggest read-
ing Chapter 1 on page 25, which talks about installing and running Ruby, followed by the
introduction in Chapter 2. From there, you may want 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, which begins on page 325, 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. See
Appendix B, beginning on page 893, for more information.
Part I

Facets of Ruby

24
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.

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 key-
board). 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.

25
T HE C OMMAND P ROMPT 26

When you’re at the command prompt, you have access to these same folders. But, somewhat
confusingly, at the prompt they’re 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 single 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 single backslash).
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
component in this name is separated by a forward slash (on Unix) or a backslash (on Win-
dows). 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_planner\readme.txt on Windows.

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)

Now, 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 character ~ (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
I NSTALLING RUBY 27

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. How-
ever, 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.

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.
I 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)

Installing Ruby
Quite often, you won’t even need to download Ruby. It now comes preinstalled on many
Linux distributions, and Mac OS X includes Ruby (although the version of Ruby prein-
stalled on OS X is normally several minor 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), you can install it pretty simply. But first,
you have a choice to make: go for a prepackaged distribution or build Ruby from source?

Prepackaged Distributions
A packaged distribution of Ruby simply works out of the box. You install it, and it runs.
Binary distributions are prebuilt for a particular operating environment and are convenient
if you don’t want to mess around with building Ruby from source. The downside of a
packaged distribution is that you may have to take it as given: it may be a minor release
or two behind the leading edge, and it may not have the optional libraries that you might
want (although you may be able to install additional libraries using RubyGems, described
I NSTALLING RUBY 28

in a moment). If you can live with that, you’ll need to find a packaged distribution for your
operating system and machine architecture.

Windows Distributions
In the old days (where old means Ruby 1.8), things were good for Windows users. There
was a great “batteries included” package that would install not just Ruby but also a vast
array of libraries and gems. This was called the One-Click Installer, or OCI.
However, with the advent of Ruby 1.9, the situation has changed somewhat. Ruby 1.9 hasn’t
been around long, so some of the libraries that were included in the 1.8 installer have not
yet been made compatible with 1.9. As I write this, the OCI project is in a state of flux. The
maintainer, Luis Lavena, is planning on releasing a Ruby 1.9 version of the OCI in early
2009, but it may well not contain as many libraries as the 1.8 version. The situation will
improve over time. (And, if you feel strongly about this, I know Luis would welcome your
help porting stuff over.)
So, you have a couple of choices for installing Ruby 1.9 on Windows. You can visit http://rubyforge.org/proj
and see whether a one-click installer is available. If not, you can download a prebuilt binary
from ruby-lang.org.1

Linux Distributions
Most modern Linux distributions use the apt-get system (or the Synaptic GUI) to find and
install Ruby. As of November 2008, the following command installs Ruby, irb, and ri:
$ sudo apt-get install ruby1.9 libruby1.9 libreadline-ruby1.9 irb1.9
$ sudo apt-get install rdoc1.9 ri1.9

This installs all the Ruby commands with a 1.9 suffix, so you’ll need to do this:
$ ruby1.9 -v
ruby 1.9.0 (2007-12-25 revision 14709) [i486-linux]

Be aware that the version of Ruby we just installed is many months behind the current
version.
Note that you need to have superuser access to install global packages on a Unix or Linux
box, which is why we use the sudo command.

OS X Distributions
Leopard (OS X 10.5) comes with Ruby 1.8 preinstalled.2 If you want to make use of the
new Ruby 1.9 features, you’ll want to install Ruby yourself. You can do this from source,
or you can use a package management system. I personally use MacPorts.3 Once you have

1. Visit http://www.ruby-lang.org/en/downloads/, and look for Ruby on Windows.


2. At some point, it seems likely that Apple will include MacRuby. This is its own port of Ruby 1.9, tightly inte-
grated into the Objective-C runtime. In the meantime, you can download MacRuby from http://www.macruby.org.
3. http://www.macports.org/
I NSTALLING RUBY 29

the basic ports system installed, as described on its website, installing Ruby is as simple as
doing this:
$ sudo port install ruby19

As with apt-get for Linux, MacPorts currently installs the Ruby executables with a 1.9 suffix
(ruby1.9, irb1.9, and so on). If you don’t already have /opt/local/bin in your path, you’ll need
to add it. As an alternative, you could investigate http://rubyosx.com/, which claims to
offer a packaged OS X installation.

Building Ruby from Source


Because Ruby is an open source project, you can download the interpreter’s source code
and build it on your own system. Compared to using a binary distribution, this gives you
a lot more control over where things go, and you can keep your installation totally up-to-
date. The downside is that you’re taking on the responsibility of managing the build and
installation process. This isn’t onerous, but it can be scary if you’ve never installed an open
source application from source.
The first thing to do is to download the source. This comes in three flavors, all from
http://www.ruby-lang.org/en/downloads:

• The stable release in tarball format. A tarball is an archive file, much like a .zip file.
• The stable snapshot. This is a tarball, created nightly, of the latest source code in
Ruby’s stable development branch. The stable branch is intended for production code
and in general will be reliable. However, because the snapshot is taken daily, new fea-
tures may not have received thorough testing yet—the stable tarball in the previous
bullet will be generally more reliable.
• The nightly snapshot. This is again a tarball, created nightly. Unlike the stable code in
the previous two tarballs, this code is leading edge, because it is taken from the head
of the development branch. Expect things to be broken in here.
If you plan on downloading either of the nightly snapshots regularly, it may be easier to
subscribe to the source repository directly. The sidebar on page 31 gives more details.
Once you’ve loaded a tarball, you’ll have to expand the archive into its constituent files. Use
the tar command for this (if you don’t have tar installed, you can try using another archiving
utility, because many now support tar-format files).
$ tar xzf snapshot.tar.gz
ruby/
ruby/bcc32/
ruby/bcc32/Makefile.sub
ruby/bcc32/README.bcc32
: : :

This installs the Ruby source tree in the subdirectory ruby/. In that directory, you’ll find a
file named README, which explains the installation procedure in detail. To summarize, you
build Ruby on Unix-based systems using the same four commands you use for most other
open source applications: ./configure, make, make test, and make install. You can build Ruby
RUNNING RUBY 30

under other environments (including Windows)—see README.win32 in the distribution’s


win32 subdirectory as a starting point.

Source Code from This Book


We have made the source code from this book available for download from our website at
http://pragprog.com/titles/ruby3/code. 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 additional scaffolding to make the code run.

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
test to see whether Ruby is installed. Bring up a fresh command prompt, and type this:4
$ ruby -v
ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-darwin9.6.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 OS X
and installed Ruby from source, you’ll probably have to add a line like this to the file .profile
in your home directory:
PATH=/usr/local/bin:$PATH

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).
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!

4. Remember you may need to use ruby1.9 as the command name if you installed using a package management
system.
RUNNING RUBY 31

The Very Latest Ruby


For those who just have to be on the very latest, hot-off-the-press,
and untested cutting edge (as we were while writing this book), you
can get development versions straight from the developers’ working
repository.
The Ruby developers use Subversion (often abbreviated as SVN) as
their revision control system. Subversion clients can be downloaded
from http://subversion.tigris.org/. You can check files out as an
anonymous user from their archive by executing the following SVN
command:
$ svn co http://svn.ruby-lang.org/repos/ruby/trunk ruby

The complete source code tree, just as the developers last left it, will
now be copied to a ruby subdirectory on your machine.
This command will check out the head of the development tree. If you
want the Ruby 1.8 branch, change trunk to branches/ruby_1_8 in the
checkout command.

For most folks, irb—Interactive Ruby—is the tool of choice for executing Ruby interac-
tively. irb is a Ruby shell, complete with command-line history, line-editing capabilities,
and job control. (In fact, it has its own chapter beginning on page 278.) 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 end-of-file
character on your operating system (normally Ctrl+D or Ctrl+Z).
% irb
irb(main):001:0> def sum(n1, n2)
irb(main):002:1> n1 + n2
irb(main):003:1> end
=> nil
irb(main):004:0> sum(3, 4)
=> 7
irb(main):005:0> sum("cat", "dog")
=> "catdog"
irb(main):006:0> 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, TextMate, 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
RUBY D OCUMENTATION : RD OC AND RI 32

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:
Download samples/gettingstarted_2.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 parenthe-
ses.)
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 2009-04-13 13:25:51 -0500

On Unix systems, you can use the “shebang” notation as the first line of the program file:5
Download samples/gettingstarted_4.rb

#!/usr/local/bin/ruby -w
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 2009-04-13 13:25:51 -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 Explorer.

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

5. 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.
RUBY D OCUMENTATION : RD OC AND RI 33

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.
Several websites contain a complete set of the RDoc documentation for Ruby, but http://www.ruby-doc.org
is probably the best known. Browse on over, and you should be able to find at least some
form of documentation for any Ruby library. The site is adding new documentation all the
time.
The ri tool is a local, command-line viewer for this same documentation. Most Ruby distri-
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 lists
the summary information for the GC class. (For a list of classes with ri documentation, type
ri.)
$ ri GC
-------------------------------------------------------------- Class: GC
The GC module provides an interface to Ruby's mark and sweep
garbage collection mechanism. Some of the underlying methods are
also available via the ObjectSpace module.
------------------------------------------------------------------------

Class methods:
count, disable, enable, malloc_allocated_size, malloc_allocations,
start, stress, stress=

Instance methods:
garbage_collect

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 previously disabled.

GC.disable #=> false


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

If the method you pass to ri occurs in more than one class or module, ri will list all of the
alternatives.
RUBY D OCUMENTATION : RD OC AND RI 34

Reissue the command, prefixing the method name with the name of the class and a dot:
$ ri assoc
More than one method matched your request. You can refine your
search by asking for information on one of:

Array#assoc [Ruby 1.9.1]


Array#rassoc [Ruby 1.9.1]
Hash#assoc [Ruby 1.9.1]
Hash#rassoc [Ruby 1.9.1]

$ ri Array.assoc
-------------------------------------------------------- Array#assoc
array.assoc(obj) -> an_array 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.
: : :

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 my 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
suggestions@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.
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.

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.

35
RUBY I S AN O BJECT-O RIENTED L ANGUAGE 36

When you write object-oriented programs, you’re normally looking to model concepts from
the real world. Typically 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 (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.
Download samples/intro_1.rb

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 the variable my_way referenced a particular Song instance, you’d be
able to call that instance’s play method and play a particular song.
Methods are invoked by sending a message to an object. The message contains the method’s
name, along with any parameters the method may need.1 When an object receives a mes-
sage, it looks into its own class for a corresponding method. If found, that method is exe-
cuted. 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)

1. This idea of expressing method calls in the form of messages comes from Smalltalk.
S OME B ASIC RUBY 37

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, and 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 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 pass-
ing 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’s
name.length, and so on. This is part of what we mean when we say that Ruby is a gen-
uine object-oriented language.

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,
which begins on page 325, 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:
Download samples/intro_5.rb

def say_goodnight(name)
result = "Good night, " + name
return result
end
# Time for bed...
puts say_goodnight("John-Boy")
puts say_goodnight("Mary-Ellen")
S OME B ASIC RUBY 38

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 community
if you plan on distributing your code).
Methods are defined with the keyword def, followed by the method name (in this case,
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. 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 both 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 type into 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
S OME B ASIC RUBY 39

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:
Download samples/intro_10.rb

def say_goodnight(name)
result = "Good night, #{name}"
return result
end
puts say_goodnight('Pa')

produces:
Good night, Pa

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:
Download samples/intro_11.rb

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, which begins on page 106.
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:
Download samples/intro_12.rb

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
A RRAYS AND H ASHES 40

start with a lowercase letter or with an underscore. Global variables are prefixed with a
dollar sign ($), and instance variables begin with an “at” sign (@). Class variables start with
two “at” signs (@@).2 Finally, class names, module names, and constants must start with
an uppercase letter. Samples of different names are given in Table 2.1 on the next page.
Following this initial character, a name can be any combination of letters, digits, and under-
scores (with the proviso that the character following an @ sign may not be a digit). How-
ever, 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 =.

Arrays and Hashes


Ruby’s arrays and hashes are indexed collections. Both store collections of objects, acces-
sible 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.
Download samples/intro_13.rb

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.

2. 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.
A RRAYS AND H ASHES 41

Table 2.1. Example Variable and Class Names


Variables Constants and
Local Global Instance Class Class Names
name $debug @name @@total PI
fish_and_chips $CUSTOMER @point_1 @@symtab FeetPerMile
x_axis $_ @X @@N String
thx1138 $plan9 @_ @@x_pos MyClass
_26 $Global @plan9 @@SINGLE JazzSong

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:
Download samples/intro_14.rb

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 =>.
For example, you may want to map musical instruments to their orchestral sections. You
could do this with a hash:
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.
S YMBOLS 42

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 condi-
tional 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 conve-
nient 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. (The full source for the word frequency counter is on page 72.)
Download samples/intro_17.rb

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 lots of useful methods; see the discussion starting on page 67,
and the reference sections starting on pages 447 and 533, for details.

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

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)
C ONTROL S TRUCTURES 43

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 1.9 introduces a new syntax—
1.9 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]}"

produces:
An oboe is a woodwind

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:
if count > 10
puts "Try again"
elsif tries == 3
puts "You lose"
C ONTROL S TRUCTURES 44

else
puts "Enter a number"
end

Similarly, while statements are terminated with end:


while weight < 100 and num_pallets <= 30
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 method gets returns the next line from the standard input stream or nil when
end of 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

Similarly, a while loop such as this:


square = 2
while square < 1000
square = square*square
end

becomes this more concise version:


square = 2
square = square*square while square < 1000

These statement modifiers should seem familiar to Perl programmers.


R EGULAR E XPRESSIONS 45

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 typ-
ically 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 [Fri02]), 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 regular expressions starting on page 117.
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
patterns, 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 on page 125.
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
Random documents with unrelated
content Scribd suggests to you:
mouth, and the beautiful broad brow drooping with the weight of
thought, and yet with an eternal youth and freshness shining out of it
as from the morning forehead of a boy, are all remarkable, and their
harmony with each other in a placid tenderness not less so.

Chaucer’s beginnings as an author were translations from the


French and Italian. Imitations they should rather be called, for he put
himself into them, and the mixture made a new poem. He helped
himself without scruple from every quarter. And, indeed, there is
nothing more clear than that the great poets are not sudden
prodigies, but slow results. Just as an oak profits by the foregone
lives of immemorial vegetable races, so we may be sure that the
genius of every remembered poet drew the forces that built it up
from the decay of a whole forest of forgotten ones. And in proportion
as the genius is vigorous and original will its indebtedness be; will it
strike its roots deeper into the past and into remoter fields in search
of the virtue that must sustain it.

Accordingly, Chaucer, like Shakspeare, invented almost nothing.


Wherever he found anything directed to Geoffrey Chaucer he took it
and made the most of it. Indeed, the works of the great poets teach
us to hold invention somewhat cheap. The Provençal rhymers did
the best to invent things that nobody ever thought of before, and they
succeeded in producing what nobody ever thought of again. He must
be a very great poet indeed who can afford to say anything new.

In the great poets I think there is always a flavor of race or country


which gives them a peculiar nearness to those of the same blood,
and where the face of the individual nature is most marked, it will be
found that the type of family is also most deeply stamped. It is
remarkable that Chaucer, who probably spoke French as often and
as familiarly as English, who levied his contributions upon Norman,
Italian, and Latin writers, should yet have become (with an
exception) the most truly English of our poets.

In endeavoring to point out what seem to be the peculiar


characteristics of Chaucer, I think we shall find one of the chief to be
this—that he is the first poet who has looked to nature as a motive of
conscious emotion. Accordingly, his descriptions are always simple
and addressed to the eye rather than to the mind, or to the fancy
rather than to the imagination. Very often he is satisfied with giving a
list of flowers with no epithet, or one expressive of color or perfume
only.

Mr. Lowell here read a number of passages from the “Assembly of


Fowls” and other poems of Chaucer, with an extract from Spenser.

Now I observe that all Chaucer’s epithets are primary, or such as


give birth to the feeling; and all Shakspeare’s secondary, or such as
the feeling gives birth to. In truth, Shakspeare’s imagination is
always dramatic, even in his narrative poems, and it was so
abundant that the mere overflow of it has colored the very well-
springs of the English language, and especially of English poetry. On
Chaucer, nature seems to have always smiled (except in winter,
which he cordially hated), and no rumor of man’s fall appears to
have reached the trees and birds and flowers. Nature has taken to
thinking lately, and a moral jumps up out of a blossom, like a jack-in-
a-box.

Another characteristic which we find in all the poems where Chaucer


speaks in his own person is a sentiment of seclusion. He always
dreams of walking in a park or a garden walled-in on every side. It is
not narrowness but privacy that he delights in, and a certain feeling
of generous limitation. In this his poems are the antithesis of Milton’s,
which always give a feeling of great spaces.

In description it would be hard to find Chaucer’s superior. His style is


distinguished always by an energetic simplicity, which is a
combination exceedingly rare. It was apparently natural to him. But
when he is describing anything that he loves, here is an
inexpressible tenderness, as if his eyes filled with tears. His narrative
flows on like one of our inland rivers, sometimes hastening a little,
and in its eddies seeming to run sunshine; sometimes lingering
smoothly, while here and there a beautiful quiet thought, a pure
feeling, a golden-hearted verse opens as quietly as a water-lily, and
makes no ripple. In modern times the desire for startling expression
is so strong that people hardly think a thought is good for anything
unless it goes off with a pop like a gingerbeer cork.

In Chaucer’s pathetic passages (and they are many), the presence


of pity is a thing to be noticed—and the more so as he is the best
pathetic story-teller among the English, and, except Dante, among
the modern poets. Chaucer, when he comes to the sorrow of his
story, seems to croon over the thoughts, and soothe them, and
handle them with a pleasant compassionateness, as a child treats a
wounded bird which he cannot make up his heart to let go, and yet
fears to close his fingers too firmly upon.

Mr. Lowell, in illustration, read from the “Man of Law’s Tale,” and
other of the poems.

What I have said of Chaucer’s pathos is equally true of his humor. It


never invades a story, but pervades it. It circulates through all his
comic tales like lively blood, and never puddles on the surface any
unhealthy spots of extravasation. And this I take to be the highest
merit of narrative—diffusion without diffuseness.

I have not spoken yet of Chaucer’s greatest work, the “Canterbury


Tales.” He has been greatly commended for his skill in the painting of
character, and, indeed, nothing too good can be said of him in this
respect. But I think it is too much the fashion to consider Chaucer as
one of those Flemish painters who are called realists because they
never painted the reality, but only the material. It is true that Chaucer
is as minute in his costume as if he were illuminating a missal.
Nothing escapes him—the cut of the beard, the color of the jerkin,
the rustiness of the sword. He could not help this, his eye for the
picturesque is so quick and sure. But in drawing the character it is
quite otherwise. Here his style is large and free, and he emphasizes,
but not too strongly, those points only which are essential, and which
give variety to his picture without any loss to the keeping. For he did
not forget that he was painting history and not a portrait. If his
character of the good parson (which still stands not only unmatched
but unapproached by the many later attempts at the same thing)
seem an exception, it is yet in truth a confirmation of what I have
said. For, in this case, for the very sake of keeping, it was necessary
to be more full and careful, because the good parson alone must
balance the friar, the pardoner, and all the other clerical personages
who are almost unmixedly evil. Justice is always a leading quality in
great minds, and by this single figure on one side and the group on
the other Chaucer satirizes the Church, as it can only be satirized, by
showing that it contrasts with that true religion with which it should be
identical. And was there ever anything so happy as Chaucer’s satire!
Commonly satire is unhappy, but Chaucer’s is positively more kindly
than the panegyric of some poets.

In calling Chaucer genial I chose the word with forethought. This


geniality made it impossible that his satire should be intellectual. The
satire of the intellect deals with the outside only, trying the thing
satirized by a rigid standard. But it results from Chaucer’s genial
temperament that justice in him is so equipoised by love that it
becomes mercy, which is the point of rest between absolute law and
human frailty. Therefore Chaucer, properly speaking, is not a satirist
but a humorist; in other words, his satire is imaginative, and thus, in
perfect subordination to narrative (though not to dramatic) art, he
makes his characters satirize themselves. I suppose that no
humorist ever makes anybody so thoroughly an object of satire as
himself—but then one always satirizes himself kindly because he
sees all sides. Falstaff is an example of this. Now this is just the
character of imaginative or humorous satire, that the humorist enters
his subject, assumes his consciousness, and works wholly from
within. Accordingly when Chaucer makes his Frere or Pardoner
expose all his own knaveries, we feel not as if he said, “See what a
precious scamp this fellow is,” but “This is the way we poor devils
play fantastic tricks before high heaven.” The butt of the humorist is
Man (including himself and us); the butt of the satirist is always
individual man. The humorist says we; the moralist and satirist, thou.
Here is the strength of the great imaginative satirist of modern times,
Mr. Thackeray.

In satire, the antithesis of Chaucer is Pope; as a painter of life and


manners, Crabbe, who had great powers of observation without
imagination. Therefore what is simplicity in Chaucer is poverty in
Crabbe.

Chaucer is the first great poet who held up a mirror to contemporary


life in its objectivity, and for the mere sake of its picturesqueness—
that is, he is the first great poet who has treated To-day as if it were
as good as Yesterday. Dante wrote life also, but it was his own life,
and what is more, his own interior life. All his characters are
represented in their relation to that. But Chaucer reflected life in its
large sense—the life of men, from the knight to the ploughman. Thus
it is that he always quietly and naturally rises above the Conventional
into the Universal. And so his great poem lives forever in that
perennial contemporaneousness which is the great privilege of
genius. Thus the man of genius has a double immortality—in heaven
and on earth at the same time; and this is what makes it good to be
a genius at all, that their beauty and their goodness live after them,
and every generation of men can say of them—They are our friends
also.

I know not how to sum up what we feel about Chaucer except by


saying, what would have pleased him most, that we love him. I would
write on the first page of his volume the inscription which he puts
over the gate in his “Assembly of Fowls”:

Through me men go into the blissful place


Of the heart’s heal, and deadly woundes cure;
Through me men go into the welle of Grace,
Where green and lusty May shall ever endure.
This is the way to all good aventure;
Be glad thou reader, and thy sorrow offcast.
All open am I, pass in, and hye thee fast.
LECTURE VI
SPENSER

(Friday Evening, January 26, 1855)

VI
Chaucer had been in his grave one hundred and fifty years before
England had secreted choice material enough to produce another
great poet. Or, perhaps, we take it for granted that Nature
understands her own business too well to make such productions
cheap. Beauty, we know, has no charm like that of its eternal
unexpectedness, and the best delight is that which blossoms from a
stem of bare and long days.

Or is it that the spirit of man, of every race of men, has its fatal ebbs
and floods, its oscillations between the fluid ideal and the solid
matter-of-fact, so that the doubtful line of shore between is in one
generation a hard sandy actuality, with only such resemblances of
beauty as a dead sea-moss here and there, and in the next is
whelmed with those graceful curves of ever-gaining, ever-receding
foam, and that dance of joyous spray which knows not, so bright is it,
whether it be sea or sunshine.

What English Poetry was between Chaucer and Spenser there is no


need to say. Scotland had given birth to two or three poets of that
kind which is qualified by the epithet national, which is as much as
saying that they took account only of the universe to the north-
northeast corner of human nature instead of the whole
circumference of it. England in the meanwhile had been enriched
with Sternhold and Hopkins, but on the whole, the most important
event between the death of Chaucer and the publication of the
“Faëry Queene” was the introduction of blank verse. Perhaps the
blank poetry suggested it.

Before the “Faëry Queene,” also, two long poems were printed and
popular—the “Mirror for Magistrates,” and “Albion’s England.” How
the first of these was ever read it is hard to conceive, unless we
accept the theory of some theologians that our earth is only a kind of
penal colony where men are punished for sins committed in some
previous state of existence. The other was the work of one Warner, a
conveyancer, and has a certain philological value now from its
abounding in the popular phrases of the day. It is worth notice, also,
as containing the most perfect example in the English language of
what is called a conceit. It occurs in his account of Queen Elinor’s
treatment of Fair Rosamond:

With that she dashed her on the lips


So dyed double red;
Hard was the heart that struck the blow,
Soft were the lips that bled.

Which is nonsense and not poetry, though Dr. Percy admired it. Dr.
Donne, and the poets whom Dr. Johnson called metaphysical (as if
all poets are not so), is thought to be full of conceits. But the essence
of a conceit is not in a comparison being far-fetched,—the
imagination can make fire and water friendly when it likes,—but in
playing upon the meanings of two words where one is taken in a
metaphorical sense. This is a mark of the superficial mind always;
whereas Donne’s may be called a subterficial one, which went down
to the roots of thought instead of playing with its blossoms.

Not long after the “Faëry Queene” were published the “Polyolbion” of
Drayton, and the “Civil Wars” of Daniel. Both of these men were
respectable poets (especially Drayton), but neither of them could
reconcile poetry with gazetteering or chronicle-making. They are as
unlike as a declaration in love and a declaration in law.
This was the period of the Saurians in English Poetry, interminable
poems, book after book and canto after canto, like far-stretching
vertebræ, prodigious creatures that rendered the earth unfit for the
dwelling of Man. They are all dead now, the unwieldy monsters—
ichthyo-, plesio-, and megalosauri—they all sleep well, and their
huge remains are found imbedded in those vast morasses, the
“Collections of the Poets.” We wonder at the length of face and
general atra-bilious look that mark the portraits of that generation;
but it is no marvel when even the poetry was such downright hard
work. Poems of this sort might have served to while away the three-
centuried evening of antediluvian lives. It is easy to understand how
our ancestors could achieve great things when they encountered
such hardships for mere amusement. If we agree with Horace in
pitying the pre-Homeric heroes because they were without poets, we
may sincerely commiserate our forefathers of that generation
because they had them. The reading of one of these productions
must have been nearly as long a business as the taking of Troy, and
deserved a poet to sing it. Perhaps fathers, when their time on earth
was up, folded the leaf down and left the task to be finished by their
sons—a dreary inheritance.

The popularity of such works shows the insatiable thirst of the


human soul for something which at least tried to be beyond mere
matter-of-fact. This thirst for the ideal transmuted these books into
poetry, just as the eternal drought of the desert turns muddy water
into nectar, and the famine of the shipwrecked sailor gives a flavor
beyond French cookery to a soup made of old shoes (potage aux
choux). But meanwhile Nature, who loves surprises, was quietly
preparing a noble one. A new poet had been born, and came upon
that arid century fresh and dewy as out of the first dawn that waked
the birds in Eden. A great poet is always impossible—till he comes,
and then he seems the simplest thing in the world to the
commentators. He got this notice here and the other there; similar
subjects had been treated by such a one, and the metre first used by
another. They give us all the terms of the equation; satisfy us that a
plus b minus c equals x, only we are left in the dark as to what x is.
The genius continues to be an unknown quantity. The great poet is
as original as to-morrow’s sunrise, which will take the old clouds and
vapors, and little household smokes of our poor, worn-out earth to
make a miracle out of, and transfigure the old hills and fields and
houses with the enchantment of familiar novelty. It is this power of
being at once familiar and novel that distinguishes the primary poets.
They give us a new heaven and a new earth without the former
things having passed away,—whose very charm is that they have
not,—a new heaven and a new earth that we can possess by the
fireside, in the street, and the counting-room.

Edmund Spenser was born, like Chaucer, in London, in 1553, when


Cervantes was six years old. That sixteenth century was a
miraculous one. Scarce any other can show such a concurrence of
great brains. Mothers must have expected an attack of genius
among their children, as we look for measles or whooping-cough
now. While Spenser was yet delving over the propria quæ maribus,
Shakspeare was stretching out his baby arms and trying to get the
moon to play with, and the little Bacon, chewing upon his coral, had
already learned the impenetrability of matter. It almost takes one’s
breath away to think that at the same time “Hamlet” and the “Novum
Organon” were at the mercy of teething and the scarlet fever, unless,
indeed, destiny takes care to lock the doors against those child-
stealing gypsies when she leaves such precious things about.

Of Spenser’s personal history we know very little. He was educated


at Cambridge, where he took the degree of Master of Arts in 1576.
He is supposed to have passed the three following years with some
relations in the country, where he wrote verses and fell in love with a
lady whom he calls Rosalind, and of whom we know nothing further
unless we are satisfied to take the portrait which Shakspeare has
associated forever with the name which he complimented by
adopting. He is said to have been employed to carry a despatch or
two, but Lord Burleigh did not fancy him. Poor Lord Burleigh! Sidney
and Raleigh, however, were luckier. He was recommended to the
great queen, and received at last a grant of Kilcolman Castle and
three thousand acres of land in the south of Ireland. Here the “Faëry
Queene” was in great part written. At last came a rebellion. The wild
kernes and gallow-glasses had not the delicacy of the Emathian
conqueror, and they burned the castle, from which Spenser and his
wife with two of their children barely escaped, leaving an infant to
perish in the flames. Spenser came to London and died broken-
hearted three months afterward, on the 16th of January, 1599. That
rare nature was like a Venice glass, meant only to mantle with the
wine of the sunniest poetry. The first drop of poisonous sorrow
shattered it.

In 1579 Spenser published the “Shepherd’s Calendar,” a series of


twelve eclogues, one for each month in the year. In these poems he
professedly imitated Chaucer, whom he called his master, but
without much success. Even with the light reflected upon them from
the lustre of his great poem, one can find but little in them that is not
dull. There are indications in these poems, however, here and there,
of a nice ear for harmony in verse.

Spenser was the pure sense of the Beautiful put into a human body
only that it might have the means of communicating with men. His
own description of Clarion, the butterfly in his “Muiopotmos,” gives,
perhaps, the best possible idea of his own character.

Over the fields, in his frank lustiness,


And all the champaign o’er, he soared light
And all the country wide he did possess,
Feeding upon their pleasures bounteously,
That none gainsay, and none did him envy.

The woods, the rivers, and the meadows green,


With his air-cutting wings he measured wide,
Nor did he leave the mountains bare unseen,
Nor the rank grassy fens’ delights untried;
But none of these, however sweet they been,
Mote please his fancy, or him cause to abide;
His choiceful sense with every change doth flit,
No common things may please a wavering wit.
To the gay gardens his unstaid desire
Him wholly carried, to refresh his sprights;
There lavish Nature, in her last attire,
Pours forth sweet odors and alluring sights;
And Art, with her contending, doth aspire
To excel the natural with made delights,
And all that fair or pleasant may be found,
In riotous excess doth there abound.

There he arriving, round about doth flie,


From bed to bed, from one to the other border,
And takes survey with curious busy eye,
Of every flower and herb there set in order;
Now this, now that, he tasteth tenderly,
Yet none of them he rudely doth disorder;
He with his feet their silken leaves displace,
But pastures on the pleasures of each place.

And evermore with most variety


And change of sweetness (for all change is sweet),
He casts his glutton sense to satisfy,
Now sucking of the sap of herbs most meet,
Or of the dew which yet on them doth lie,
Now in the same bathing his tender feet;
And then he percheth on some branch thereby
To weather him, and his moist wings to dry.

And whatsoe’er of virtue good or ill,


Grew in his garden fetched from far away,
Of every one he takes and tastes at will,
And on their pleasures greedily doth prey;
Then, when he hath both played and fed his fill,
In the warm sun he doth himself embay,
And there him rests in riotous suffisance
Of all his gladfulness and kingly joyance.
What more felicity can fall a creature
Than to enjoy delight with liberty?
And to be lord of all the works of Nature,
To reign in the air from earth to highest sky?
To feed on flowers and weeds of glorious feature,
To take whatever thing doth please the eye?
Who rests not pleased with such happiness
Well worthy he to taste of wretchedness.

What poet has ever left us such a portrait of himself as this? In that
butterfly Spenser has symbolized the purely poetical nature. It will be
seen that there is no recognition of the moral sense whatever. The
poetic nature considered abstractly craves only beauty and delight—
without any thought beyond—

And whatsoe’er of virtue good or ill,


To feed on flowers and weeds of glorious feature.

The poetical temperament has nowhere been at once so exquisitely


defined and illustrated. Among poets, Spenser stands for the
temperament personified.

But how did it happen that this lightsome creature, whose only
business was

To reign in the air from earth to highest sky,

should have attempted in his greatest work to mix together two such
incoherent things as sermon and poem? In the first place, the age
out of which a man is born is the mother of his mind, and imprints
her own likeness more or less clearly on the features of her child.
There are two destinies from which no one can escape, his own
idiosyncrasy, and that of the time in which he lives. Or shall we say
that where the brain is in flower of its conceptions, the very air is full
of thought-pollen, or some wandering bee will bring it, we know not
from what far field, to hybridize the fruit?

In Spenser’s time England was just going through the vinous stage
of that Puritanic fermentation which became acetous in Milton, and
putrefactive in the Fifth Monarchy men. Here was one motive. But,
besides this, it is evident that Spenser’s fancy had been colored by
the Romances which were popular in his day; and these had all been
allegorized by the monks, who turned them into prose. The
adventure of the San Grail in the “Morte d’Arthur” reads almost like
an extract from the “Pilgrim’s Progress.” Allegories were the fashion,
and Spenser put one on as he did a ruff, not because it was the most
convenient or becoming thing in the world, but because other people
did.

Another reason is probably to be found in the nature of the man


himself. The poetical temperament, when it comes down to earth
and mingles with men, is conscious of a certain weakness. On the
unsubstantial skyey floors of its own ideal world it walks firmly
enough, and speaks the native language of the shadowy population
there. But there is a knell at which that beautiful land dissolves like
the baseless fabric of a vision—and that is the dinner bell. The
poetical temperament becomes keenly conscious that it also has a
stomach. It must dine, and commonly it likes rather better dinners
than other people. To this end it must carry its wares to market
where the understanding is master. Will the understanding pay hard
money for the flowers of speech! Only what is practical will do there.
“Fine words,” grumbles the Understanding proverbially, “butter no
parsnips; and then, to make the matter worse, the parsnips are
ideal.” “But, my dear sir,” remonstrates Temperament mildly—“Dear
me no dears,” growls Understanding. “Everybody must earn his own
salt—I do.” “Let me read you my beautiful poem.” “Can’t comprehend
a word of it. The only language I know a word of is my old mother
tongue, the useful. Look at the towns and ships I’ve built. Nothing
ideal there, you’ll find. Ideal, I suppose, is a new-fangled way of
spelling idle. It won’t go here.” Suddenly the useful seems a very
solid and powerful thing to our poor friend, the Poetic Temperament.
It begins to feel a little absurd in talking enthusiasm to such a matter-
of-fact generation. The problem is how to translate the ideal into the
useful. How shall Master Edmund Spenser make himself
comprehensible to Master John Bull? He will try a picture-book, and
a moral one, too—he will write an Allegory.

Allegory is the Imagination of the Understanding, or what it supposes


to be, which is the same thing. It is the ideal in words of one syllable,
illustrated with cuts, and adapted to the meanest comprehension.

Spenser was a good and pure-minded man, and wished probably to


combine the sacred office of Teacher with that of Poet. The
preaching part of him came afterwards in Jeremy Taylor, who was
Spenser with his singing-robes off.

Spenser’s mind was so thoroughly imbued with the beautiful that he


makes even the Cave of Mammon a place one would like to live in.

I think it is the want of human interest that makes the “Faëry


Queene” so little read. Hazlitt has said that nobody need be afraid of
the allegory; it will not bite them, nor meddle with them unless they
meddle with it. It was the first poem I ever read, and I had no
suspicion of any double meaning in it. If we think of the moral as we
read it will injure the effect of the poem, because we have an
instinctive feeling that Beauty includes its own moral, and does not
need to have it stuck on.

Charles Lamb made the most comprehensive criticism upon


Spenser when he called him the “poets’ poet.” This was a magic
mirror which he held up to life, where only shapes of loveliness are
reflected. A joyous feeling of the beautiful thrills through the whole
poem.

I think that Spenser has come nearer to expressing the unattainable


something than any other poet. He is so purely a poet of beauty that
with him the meaning does not modulate the music of the verse, but
the music is a great part of the meaning. No poet is so splendidly
superfluous as he. He knows too well that in poetry enough is
parsimony. The delight of beauty is that it is like a fountain, forever
changing, forever the same, and forever more than full.

Spenser has characterized his own poem in the song which the
Sirens sing to Sir Guyon in the twelfth canto of the second book. The
whole passage also may be called his musical as distinguished from
his picturesque style.

In reading Spenser one may see all the great galleries of painting
without stepping over his threshold. Michael Angelo is the only artist
that he will not find there. It may be said of him that he is not a
narrative poet at all, that he tells no stories, but paints them.

I have said that among our poets Spenser stands for the
personification of the poetic sense and temperament. In him the
senses were so sublimed and etherealized, and sympathized so
harmoniously with an intellect of the subtlest quality that, with Dr.
Donne, we “could almost say his body thought.” This benign
introfusion of sense and spirit it is which gives his poetry the charm
of crystalline purity without loss of warmth. He is ideal without being
merely imaginative; he is sensuous without any suggestion of flesh
and blood. He is full of feeling, and yet of such a kind that we can
neither call it mere intellectual perception of what is fair and good
and touching, nor associate it with that throbbing warmth which leads
us to call sensibility by its human name of heart. In the world into
which he carries us there is neither space nor time, and so far it is
purely intellectual, but then it is full of form and color and all earthly
gorgeousness, and so far it is sensual. There are no men and
women in it, and yet it throngs with airy and immortal shapes that
have the likeness of men and women.

To appreciate fully the sensuous intellectuality of this divine poet,


compare him for a moment with Pope, who had an equal subtlety of
brain without the joyous poetic sense. Pope’s mind was like a
perfectly clear mirror hung in a drawing-room, and reflecting with
perfect precision of outline and vividness of coloring, not man, but
good society, every grace and every folly that belong not to human
nature in its broad meaning, but as it is subordinated by fashion. But
Spenser is like a great calm pool that lies brooding in delicious
reverie over its golden sands in some enchanted world. If we look
into it we know not if we see the shadows of clouds and trees and
castles, of bright-armored knights and peerless dames that linger
and are gone; or whether those pellucid depths are only a
mysterious reservoir, where all the fairest dreams of our youth,
dreams that were like hopes, and hopes that were but dreams, are
visionarily gathered. Anon a ripple, born of no breeze, but of the
poet’s own conscious joy, startles it into a dance of sunshine that
fades away around its shores in a lapsing murmur that seems the
shadow of music rather than its substance.

So entirely are beauty and delight the element of Spenser, that


whenever in the “Faëry Queene” you come upon a thought or moral
reflection it gives you a shock of unpleasant surprise, a kind of grit,
as when one’s teeth close upon a bit of gravel in a dish of
strawberries and cream. He is the most fluent of our poets.
Sensation passing over through emotion into reverie is the
characteristic of his manner.

And to read him puts one in the condition of reverie—a state of mind
in which one’s thoughts and feelings float motionless as you may
see fishes do in a swift brook, only vibrating their fins enough to keep
themselves from being swept down the current, while their bodies
yield to all its curvings and quiver with the thrills of its fluid and
sinuous delight. It is a luxury beyond luxury itself, for it is not only
dreaming awake, but dreaming without the trouble of doing it
yourself; letting it be done for you, in truth, by the finest dreamer that
ever lived, who has the art of giving you all his own visions through
the medium of music.

Of the versification of Spenser we need attempt no higher praise


than that it belonged to him. If we would feel the infinite variety of the
Spenserian stanza, as Spenser uses it, its musical intricacies, its
long, sliding cadences, smooth as the green slope on the edge of
Niagara, we have only to read verses of the same measure by other
poets.
As showing his pathos, Mr. Lowell read Una’s lament on her
desertion by the Red Cross Knight, and other pieces, calling
attention particularly to the fact that his females were not women,
like those of Shakspeare, but ideal beings.

We are accustomed to apologize for the grossness of our favorite old


authors by saying that their age was to blame, and not they. Spenser
needs no such excuses. He is the most perfect gentleman among
poets. Through that unrefined time, when ladies drank a quart of ale
for breakfast, and even Hamlet can say a coarse thing to Ophelia,
Spenser passes pure and chaste as another Sir Galahad.

Whoever can endure unmixed delight, whoever can tolerate music,


and painting, and poetry, all in one, whoever wishes to be rid of
thought and to let the busy anvils of the brain be silent for a time, let
him read in the “Faëry Queene.” There is a land of pure Heart’s Ease
where no ache or sorrow of spirit can enter. If there be any poet
whom we can love and feel grateful toward, it is Edmund Spenser.
LECTURE VII
MILTON

(Tuesday Evening, January 30, 1855)

VII
Between Spenser and Milton occurred the most truly imaginative
period of English poetry. It is the time of Shakspeare and of the other
dramatists only less than he. It seems to have been the moment in
which the English mind culminated.

Even if we subtract Shakspeare, the age remains without a parallel.


The English nature was just then giving a great heave and yearn
toward freedom in politics and religion, and literature could not fail to
partake of the movement.

A wave of enthusiasm seemed to break over England; all that was


poetical in the people found expression in deed or word. Everything
tasted of it—sermons and speeches as well as verses. The travelers
could not write a dry journal, but they somehow blundered into a
poetical phrase that clings to the memory like a perfume. The
sensations of men were as fresh as Adam’s, and the words they
found to speak them in could be beautiful or fragrant with as little
effort as it costs violets to be blue.

It is a remarkable fact that the poetry of Shakspeare is at the same


time more English and more universally human than any that was
ever written. The two great poets who came before Shakspeare had
both of them enlarged the revenues of the English muse. Chaucer
had added character and incident, and had shown the capacities of
the language and of the metre. Spenser left it enriched with a luxury
of diction, with harmony of verse, and with the lovely images of the
classical mythology. But Shakspeare came in like an unthrift heir. He
squandered everything. From king to clown he used up all character;
there is no passion, or fancy, or feeling that he has not spent; no
question of philosophy, morals, politics, or metaphysics that he has
not solved; he poured out all the golden accumulations of diction like
water. And his younger brethren, the other dramatists, helped him.
What was there left? Certainly, this wonderful being has expressed
every sentiment, every thought, that is universal in its relations. All
the poetry of this world he exhausted. Accordingly, in the time
immediately following this splendidly imaginative period, we find only
a development of fancy under one or other of its disguises. Fancy
deals with limited and personal experiences, and interests us by the
grace or perfectness of its expression of these. The Dramatists were
tremendously in earnest, as they had need to be, to please a people
who were getting in earnest themselves. But now the time itself was
preparing a drama, and on no mimic scene, but with England for a
stage and with all Europe for spectators. A real historical play was in
rehearsal, no petty war of York and Lancaster, but the death-grapple
of two eras. The time was in travail with the Ishmael of Puritanism
who, exiled from his father’s house, was to found here in this
Western wilderness an empire for himself and his wandering
descendants. England herself was turning poet, and would add her
rhapsody to the great epic of the nations.

That was a day of earnest and painful thinking, and poetical


temperaments naturally found relief in turning away from actual life
to the play of the fancy. We find no trace of high imagination here.
Certainly, Herbert and Vaughan and even Quarles are sometimes
snatched into something above common fancy by religious fervor,
but how cold and experimental is the greater part of their poetry—not
poetry, indeed, but devotional exercises in verse. Cowley wrote
imaginary love-songs to an imaginary mistress, and Waller the same
sort of stuff to a real one. Catullus revived in Herrick, a country
parson. Wither, a Puritan, wrote some poems full of nature and
feeling, and remarkable for purity of sentiment. Donne, a deep
thinker, carried on his anatomical studies into his verse, and
dissected his thoughts and feelings to the smallest nerve. A great
many nice things got said, no doubt, and many charming little poems
were written—but the great style appears no longer.

It was during this lull, as we may call it, that followed the mighty day
of the Dramatists, that Milton was growing up. He was born in
London on the ninth of December, 1608, and was therefore in his
eighth year when Shakspeare died. His father was of a good family,
which still adhered to the Roman Catholic faith. What is of more
importance, he was disinherited by his father for having adopted
Puritan principles; and he was a excellent musician. Milton was very
early an indefatigable student, even in his twelfth year seldom
leaving his books before midnight. At the university he was
distinguished as a Latin scholar and writer of Latin verses. He was
intended for the Church, but had already formed opinions of his own
which put conformity out of the question. He was by nature an
Independent, and could not, as he says, “subscribe slave.”

Leaving the university in 1632, he passed the five following years in


a studious seclusion at his father’s house at Horton, in
Buckinghamshire. During these five years he wrote most of his
smaller poems. In 1638 he set out for Italy. The most important
events of his stay in that country were his meetings with Galileo, and
the Marquis Manso, who had been Tasso’s friend. After refreshing
his Protestantism at Geneva, he passed through France and came
back to England to find the Civil War already begun.

Dr. Johnson sneers at Milton for having come home from Italy
because he could not stay abroad while his countrymen were
struggling for their freedom, and then quietly settling down as a
teacher of a few boys for bread. It might, with equal reason, have
been asked of the Doctor why, instead of writing “Taxation no
Tyranny,” he did not volunteer in the war against the rebel American
provinces? Milton sacrificed to the cause he thought holy something
dearer to him than life—the hope of an earthly immortality in a great
poem. He suffered his eyes to be put out for the sake of his country
as deliberately as Scævola thrust his hand into the flame. He gave to
freedom something better than a sword—words that were victories.
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!

ebookgate.com

You might also like