0% found this document useful (0 votes)
7 views

Programming Ruby 1 9 3rd Edition Dave Thomas - Download the ebook today and own the complete content

The document provides information about various programming ebooks available for instant download at ebookgate.com, including titles on Ruby, Elixir, Visual Basic, Cocoa, and Python. It highlights the ease of access to digital formats such as PDF, ePub, and MOBI. Additionally, it mentions the Pragmatic Programmers' guide to Ruby, emphasizing its revised content and educational resources.

Uploaded by

sannahjuraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Programming Ruby 1 9 3rd Edition Dave Thomas - Download the ebook today and own the complete content

The document provides information about various programming ebooks available for instant download at ebookgate.com, including titles on Ruby, Elixir, Visual Basic, Cocoa, and Python. It highlights the ease of access to digital formats such as PDF, ePub, and MOBI. Additionally, it mentions the Pragmatic Programmers' guide to Ruby, emphasizing its revised content and educational resources.

Uploaded by

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

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

Programming Ruby 1 9 3rd Edition Dave Thomas

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

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

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
Other documents randomly have
different content
France of incontestable progress in the way of justice, liberty, and
social happiness, cannot have become, all of a sudden, a cause of
decline. Practically, in spite of all its ills and all its shortcomings, the
present century has no cause to dread a comparison with past
centuries. There never has been any epoch in the history of French
society in which it would have bettered its condition by halting, or
to which it should wish to return.

I revert to my question; what perils, what obstacles, do our social


institutions and our manners oppose to the establishment of Liberty
with effect and upon a lasting footing? Is Christianity of a nature to
stand us in good stead, or to hurt us in such a work?

All earnest men, all clear-sighted men, at the present day, whether
they are Conservatives or Liberals, Christians or Free-thinkers,
Catholics or Protestants, are unanimous in deploring the
preponderance of material interests, the thirst for physical and
vulgar pleasures, and the habits of selfishness and effeminacy
which they generate.

They are right; we have indeed here an evil greater, when we


consider what is the mission of our epoch, than perhaps even those
believe it to be who deplore it. The Emperor Napoleon said, in a
phrase marked by all the clear and forcible colouring of his habitual
language:—"I do not fear conspirators who rise at ten o'clock in the
morning, and who cannot do without a fresh shirt." [Footnote 13]

[Footnote 13: "Je ne crains pas les conspirateurs qui se


lèvent à dix heures du matin, et qui ont besoin de
mettre une chemise blanche."]

There is no question of conspirators here, and for the soul to be


vigorous it is not essential that the care of the person should be
neglected. What concerns those who would be free, whether
individuals or nations, is that they should not have their attention
essentially absorbed by considerations affecting merely their
material prosperity, or their petty personal comforts; they have
especially to guard themselves against selfishness and
Epicureanism. Whether his tastes be refined or gross, the Epicurean
does not readily resign himself to make either effort or sacrifice;
but he is not difficult to content if he is permitted to enjoy his
pleasures and his repose. Selfishness, even where it is sober and
gentle, is a cold and sterile passion, it owes its empire to its
success in enervating and lowering a man's nature. Liberty calls for
a character of more strength, higher aspirations, greater power of
resistance; a state of soul offering freer action to moral sympathy
and disinterested motives. It is precisely here that Christianity can
supply modern society with that of which it stands in need.
Christianity teaches all men, the great and the small, the rich and
the poor, not to devote all their lives to material things; she
summons them to more elevated regions, and whilst she inspires
them with a purer ambition, she opens to them a fairer hope even
of happiness. The Christian, whether his station be powerful or
humble, and his aspirations ambitious or modest, can never find an
exclusive object of attention, or an exclusive motive to action, even
in that principle of interest which politicians, using the word in its
best sense, vainly imagine to be a panacea. Man, whether towards
his fellow-creatures, or on his own account, has another object to
pursue, other laws to accomplish, other sentiments to display and
to satisfy: he can neither be an Epicurean nor an Egotist.

This is the first and the greatest of the services which Christianity
can and does render in our days to every society which aspires to
Liberty. I proceed to mention a second service.

There is no liberty without a large measure of license. They are


dreamers who hope to enjoy the benefits of the one without
incurring the risk, and undergoing the inconveniences, of the other.
They, too, are dreamers who believe that license will ever be
effectually repressed by penalties, courts of justice, or measures of
Police. Two things are certain; the one is, that it is idle to attempt
to repress license completely in a free country; the other, that the
moral and preventive forces of society itself are alone to be relied
upon, both by governments and nations, to enable them to support
that license which they cannot suppress. Christianity is the most
efficacious, the most popular, and the most approved of these
forces. It is efficacious against license for two reasons and in two
ways. In principle, Christianity maintains to Authority its right and
its rank intact; without humbling it before Liberty, Christianity yet
recognises the rights of Liberty, and demands that these should be
admitted; in fact Christianity inspires men with a sentiment, with
which authority cannot dispense, respect. The absence of respect is
the most serious danger to which authority is exposed; authority
suffers much more from insult than from attack; it is precisely to
the task of systematically insulting and debasing authority, that its
most ardent opponents, in our days, address themselves with most
passion and with most art. There exist licentious, turbulent, and
insolent persons in Christian societies, just as such exist in other
societies; but Christian principles and Christian habits make and
maintain friends to Order in the great mass of the people as well as
in the higher classes, friends to order, who respect order both in
law and in morals, men whom licentious and insulting; conduct
shock as much as they terrify, and who, equally free, appeal in
their own favour to the maxims and the arms of Liberty. History
supplies us on this subject with conclusive examples. The nations of
Christendom are the only nations to which license has not brought
as a final consequence anarchy and despotism,—the only nations
which, although they have on different occasions and by salutary
reactions experienced the excesses both of power and of liberty,
have not succumbed under them morally and politically. Neither the
states of Pagan Antiquity nor those of the East, whether Bouddhist
or Mussulman, have stood such trials; these have had their days of
healthy vigour and even of glory; but when the evils which license
or tyranny generated have once come upon them, they have fallen
irretrievably, and all their subsequent history has merely been that
of a decline more or less rapid, more or less stormy, more or less
apathetic.
It is the honour of the Christian Religion that it has within it that
which can cure states of their maladies, as well as individuals of
their errors; and that, by the belief which it generates, and the
sentiments which it inspires, it has already more than once
furnished, sometimes to the friends of Order, and sometimes to the
friends of Liberty, a refuge in their reverses, as well as strength to
recover lost ground.

It would be as imprudent as ungrateful in these days for the friends


of Liberty to ignore this grand fact and its salutary admonishment.
They are called to a work much more difficult than any that they
have hitherto had to accomplish: their task is no longer merely to
search after guarantees for Liberty against the encroachments of
pre-existent Power, or the accidental and transient ebullition of
License. They have to reconcile the normal and constitutional
dominion of Democracy with Liberty, and with the regular action
and permanence of Liberty. Until modern times, political liberty,
wherever it has existed, has been the result of the simultaneous
presence and of the conflict of different forces of society, no one of
them strong enough to rule alone, but each too weak to resist
efficaciously the attack of the others; at one time the Crown, at
another the Aristocracy, at another the Church, each previously
powerful and independent, have lived side by side with Democracy
when Democracy has had limits and restrictions imposed upon its
power and success; but at the present day, there are amongst us
no distinct surviving influences which are powerful enough to play a
similar part in society and in the government. The Crown, the
Aristocracy, and the Church are no longer anything but frail wrecks
of the past, or instruments created by the Democracy, and indebted
to it for a borrowed force. Is this to be henceforth the permanent
condition of human society, or is it only a phase, more or less
transitory, of a series of ages and of revolutions, which fresh ages
and fresh revolutions will hereafter profoundly modify? Futurity
must decide. In any case, it is only under the exclusive dominion of
a single force, Democracy, that in these days free institutions can
be founded.
That every dominant force when single is tempted to commit
abuses and to become tyrannical, is a truth so much in accordance
with the lessons of experience and with the conclusions of reason,
that no pains need be taken to insist upon it. Not to speak of the
dangerous acclivity upon which Democracy, in common with all
other forces, is placed, it has peculiar characteristics which are not
of a nature to set the friends of Liberty at their ease. Democracy
derives its origin and power from the right of every human will, and
from the majority of human wills. Truth and error press so very
closely upon each other in this system, that Liberty is placed in a
position of great peril. Man's volition is entitled to every respect;
but it is not all its law to itself, nor is it in itself essentially a law at
all: it is bound to another law, which does not emanate from itself,
and which comes to it from a higher source than man, and which it
is as unable to abrogate as it was to create. The law paramount is
the moral law,—the law laid down by God, to which all wills of
men, whatever their number, are bound to submit. Democracy,
essentially busied with the wills of men, is always inclined to
attribute to them the character and the rights of divine law. Man
occupies so much space in this form of government, and has so
elevated a position there, that he easily forgets God—easily takes
himself for God. The result is a sort of political polytheism, which,
unless it appeals to a gross, material arbitrament, and to the
majority of human wills, is incapable of arriving at that unity of law
and of action, with which no society or government can dispense. I
do not say that the individual man, and that numbers of men, are
the only principles, but I do say, that they are principles
characteristic of Democracy; it is against the absolute dominion of
these two principles that Democracy has, in the interest of its own
honour and of its own safety, to be incessantly admonished and
defended. A royal sage enjoined that he should be saluted every
morning with the words, "Remember thou art man." This sublime
and prudent admonition is no less needful for Democracy than for
Royalty, and it is precisely the salutary service which is rendered to
it by Christianity. In Christianity there is a light, a voice, a law, a
history, which does not come from man, but which, without
offending his dignity, sets him in his proper place. No belief, no
institution, exalts man's dignity so highly, and at the same time so
effectually represses his arrogance. The more democratic a society
is, the more it is important that this double effect shall take place
within it. Christianity alone has this virtue.

I am aware of the capital objection made to its empire. "The Physic


without the Physicians," exclaimed Rousseau, in a sally against
medical men, but the expression shows nevertheless how little he
was disposed to forget that it is possible for medicine to be good
and salutary. How often have I heard men of intelligence and men
in all other respects very worthy of consideration, exclaim, "Let me
have Religion without the priests: I am a Christian, but no friend of
the clergy." I am far from seeking to leave this difficulty unnoticed,
or to elude it. It is a difficulty of the gravest nature, not in essence,
but in the actual circumstances and state of opinions at the present
day.

As a Protestant it does not concern me. The clergy is not amongst


Protestants the object of any such uneasiness. One of the best
results, in my opinion, of the Reformation of the 16th century,
whether regarded as Lutheran or Calvinistic, as Anglican, or as the
work of other Dissidents in religion, is that it strongly cemented the
union between the ecclesiastics and the general religious
community—between the spiritual and the lay members of the
Church. The Reformation produced this effect, first, by authorising
the clergy to marry and to enter into the relations which a life of
family brings with it; and, secondly, by giving to the laity a share in
the government of the Church. The partition was not always
judicious or equitable. At one time the clergy, at another the laity,
have been transported from their natural places, and injured in
their legitimate rights; but the relations between the two classes
ceased to present the appearance of either absolutism on the one
hand, or of entire subordination on the other; the laity obtained a
voice and influence in the affairs of the flock; the priests, although
remaining religious pastors and religious magistrates, ceased to be
spiritual masters. This organisation has led to the two social
institutions combining themselves in a variety of ways. At one time
the civil power has invaded the government of the religious society,
and deprived the clergy, not merely of empire, but of
independence; at another time the two forms of society, the State
and the Church, have regulated by treaty the terms of their mutual
relations; whereas, in the United States of America, the two forms
of society have been entirely separated, and have mutually
recovered their independence; elsewhere, as amongst the Quakers
and the Moravians, all ecclesiastical authority and orders of
priesthood have been abolished, and laymen have lived in the
isolation each of his individual conscience, obedient only to its
spontaneous impulses. But amidst all this diversity, it is the
fundamental characteristic of the churches and of the sects which
issued from the Reform of the 16th century, that priests do not in
themselves constitute the necessary and sovereign mediators
between God and man's soul, nor the sole rulers of religious
society. It is particularly by virtue of this principle that the
distinction between civil life and religious life has become an
efficacious and a consecrated doctrine, and that Liberty has
resumed its right and become an active influence in religious
society itself.

But amongst Roman Catholic nations, priests are the objects of a


persistent distrust which has been the fruitful source of much
calamity to Christianity. History forbids surprise. The Roman
Catholic clergy has often presented the spectacle of ambition and
passion, of mundane and selfish interests, strangely intermixed with
faith and with earnest zeal for the furtherance of their religious
mission. Serious ills and grave abuses have resulted therefrom in
the relation of Church to State, and of priests to their flocks, and
even in the bosom of the Church itself. These are facts almost as
undisputed as they are indisputable; in proof of them the
testimony, not only of its adversaries, but of the holiest members of
the Church of Rome itself, may be invoked. Nothing is more
natural, and indeed more inevitable, than that this should have led
and should still lead, not only to ill-will towards priests, but to their
being regarded as proper subjects for attack. It is not, however, on
that account less certain that such an attack is, in our days, and as
society is at present constituted, unjust, silly, and inopportune, as
injurious to State as to Church, to Liberty as to Religion. There may
be injustice and ingratitude to institutions as well as to individuals.
From the fall of the Roman Empire, and during the rudest and most
sombre ages of modern history, the Catholic clergy, whether as
Popes, Bishops, monastic orders, or simple priests, in the midst of
their selfish pretensions and ambitious usurpations, displayed and
expended treasures of intellect, courage, and perseverance in order
to affirm and protect the immaterial and moral interests of
humanity. They did not on all occasions accept their mission to its
full extent; they did not maintain the Christian Religion in all its
breadth, and in all its evangelical disinterestedness; they had their
share in the acts of violence, iniquity, and tyranny of the different
masters of society for the time being; they often made Liberty pay
dearly for the services which they rendered to civilization; but when
Liberty has become one of the conquests of that very civilization,
the proof as well as the guarantee for its further progress, there is
injustice and ingratitude in forgetting what part the Roman Catholic
clergy effected towards the constitution of that society, the ultimate
result of which has been so glorious.

The injustice is the greater that it is now inopportune and useless.


From the acrimony, the anger, and alarm which characterise the
attacks directed at Roman Catholicism and its Priests, we might
suppose that the Inquisition was at our gates, that Rome was
making a perilous onslaught upon our civil and religious liberties,
and that we need to deploy all our force and all our passions to
repulse the domination of the Court of Rome and of its army. Was
there ever so strange a perversion of facts? For a century past, on
which side has been the movement and the aggression? Is it not
evidently the spirit of religious and political liberty which has now
the initiative, the impulsive, onward movement? The defensive is
the natural and enforced situation of the Roman Catholic Church;
Romanism is much more menaced, much more attacked by public
opinion in these days than our liberties are menaced or attacked by
her. The supreme power in the Church of Rome, the Papacy, does
indeed maintain, in principle, certain maxims and certain traditions
irreconcileable with, the actual state of opinion and society; it
continues to condemn authoritatively some of the essential
principles of modern civilization. In all earnestness, yet with every
feeling of respect, I shall here make at once use of my right, both
as a Protestant and as the citizen of a free country, to declare my
profound conviction that this systematic persistence, however
conscientious and dignified it may be, shows a great want of
religious foresight as well as of political prudence. I think that
Romanism, without abdication and without renouncing anything
that is vitally essential to itself, might assume a position in harmony
with the moral and social state in these days, and with the
conditions also vitally essential to the existence of such state. I may
add, that so long as the government of the Romish Church shall
not have accepted and accomplished this work of conciliation—
conciliation real and profound—the friends of Liberty will be
justified in keeping themselves on the alert, and in maintaining a
reserve towards it, as representing, themselves, those moral and
liberal principles which it disavows. But let them not attribute to
this disavowal a greater importance than it deserves; let them
watch the ecclesiastical power which utters it, without alarm; it has
in it nothing very menacing, nothing that opposes any effectual
barrier to the march of events; Liberalism is not the less victorious
in these days, and not the less advancing. Many faults have been
committed, and many probably will continue to be committed; as
has already been the case, we shall have perhaps many a barrier
opposed in our path, many a reactionary movement to endure, but
the general onward impulse will nevertheless be the same, and the
final result, the conquest of Liberty, religious, civil and political, not
the less a certainty.

This is no mere philosophical aspiration. It is already history. There


have been many vicissitudes in France, and many a crisis of
different kinds during the last hundred years in the struggle
between Liberalism and Roman Catholicism; the former has often
committed errors, made mistakes, by which Romanism has adroitly
profited; but at every reverse Romanism has recognised her own
defeat, and accepted some part of its consequences. The
Constituent Assembly by the civil organisation of the clergy, the
National Convention by its proscriptions, had endeavoured, the one
to enslave, the other to abolish the Catholic Church; the great
master of the revolution, Napoleon, raised it up again by the
Concordat of 1802; but the Concordat at the same time
consecrated many of the fundamental principles of the liberal
regime, and the Catholic Church of Rome consecrated Napoleon
and signed the Concordat, even whilst protesting against some of
its consequences. At the Restoration some wished to discuss again
the question of the Concordat, and to re-establish the relation
between Church and State upon their ancient foundations; but the
attempt encountered, in the ranks of the Royalists themselves, a
decisive resistance, and totally failed. Under the Government of
1830, Roman Catholicism regained its ground and resumed fresh
vigour by both using the name of Liberty and claiming its right.
When the Republic again appeared in 1848, Roman Catholicism
treated it with as much tenderness as it experienced itself from the
Republic. I pause before the actual relations of the Church of Rome
to the new Empire; Rome has paid a dear price for all that she has
received from the Empire; but even here she showed, and appears
disposed still to show, a large measure of patience and resignation.
She is right.

One fact particularly arrests my attention in the course of this


stormy history. In the midst of her reverses and her concessions,
Roman Catholicism has displayed rare and energetic virtues of
fidelity and independence. She has opposed to the bloody
persecution of Terrorism, the inexhaustible blood of her martyrs,
bishops, priests, monks, men and women; that Clergy of France,
once so vacillating in faith and so mundane in morals, bore their
cross with an indomitable sentiment of Christian honour. The
despotism of the Emperor Napoleon encountered in the person of
Pope Pius VII., in some Cardinals, and some Bishops, a passive but
firm resistance, which neither the power of the Despot, nor the
contagious servility of their contemporaries, could surmount. And
again, in these days, who can fail to perceive with what activity and
devotedness, with what sacrifices and efficacy, Roman Catholicism,
by the mere force of its native energy, upholds the cause of its
chief and of itself? If civil society had defended its liberties and its
dignities as the Church of Rome defends hers, Liberalism in France
would be farther advanced on its road and towards its object.

But let not Romanists deceive themselves: one cannot make use of
Liberty without being forced to enter into an engagement and
compromise with Liberty; one cannot appeal to Liberty without
doing homage to her; she lays her hand upon those to whom she
lends her aid. The great fact which I before invoked, the work of
reconciliation between modern society and Roman Catholicism, is
more advanced than those believe who still stand aloof from it and
oppose it. This is proved by two facts. In the very bosom of Roman
Catholicism, and from amongst its most zealous defenders, that
group of liberal Catholics was formed which has played and which
continues to play so active a part in struggling for the Liberties of
their church, and for the rights of their chief: these are at once the
ornaments of then church, and its intellectual sword; and the
publication which supports their views, the "Correspondant," is,
next to the "Revue des deux Mondes," the periodical which meets
with most success and has the greatest circulation. Passing from
this brilliant group to the more modest ranks of the Roman Catholic
clergy, I ask what is the disposition, the attitude, the conduct of
those faithful and humble priests who exercise the Christian
ministry in our provinces and in the inferior quarters of our cities;
they have not always all the science, all the mental culture, which
one might desire; but whilst adhering to Catholic faith and giving
the example of Christian lives, they live in the midst of the people;
they know it, they understand it; they are aware what the
conditions are which permit them to live with and to exercise an
influence upon the people; they enter by degrees into its
sentiments and its instincts; without premeditation, almost without
perceiving it, they become each day more and more men of their
time and country, more familiar with the ideas and liberal
tendencies of modern society. Thus at the two poles of Roman
Catholicism, in its most elevated ranks and in its popular militia, the
same result is obtained, in the one case by men of enlightened
views and of superior ability, and in the other case by men of good
sense and honesty of purpose; and thus in the Roman Church
those moral and political principles of 1789 make their way, which
form the basis of the new social edifice, of its laws, and of its
liberties.

I do not dispute, neither do I attack; I record facts as I observe


and appreciate them. And in my opinion, with reference to French
institutions,—for I speak only of France,—the essential
consequences from these facts, as far as they bear upon the
relations of Christianity to Liberty, are as follows.

I have here not a word to say respecting the Protestant Church in


France; the questions which have agitated her for some time past
are questions of faith and internal discipline, entirely aloof from any
incertitude or differences of opinion as to the rights of conscience
or of religious society in their relations to civil society. Protestantism
in France, whether orthodox or not, adopts and upholds the largest
maxims as to religious liberty, and as to the guarantee for it, in the
separation of religious life from civil life. The most zealous Liberals
have nothing more in this respect to demand from even the most
orthodox Protestants; these are indeed of their church the most
urgent in claiming for religious society the right to have its internal
autonomy, and to stand independently of the state. It is, on the
contrary, Roman Catholics, and the advocates of the essential
principles of modern society, who most dispute about the general
question of liberty.
The more I reflect, the more I am convinced that henceforth this
question can only be seriously and efficaciously dealt with in one of
two ways: the one is by the alliance of Church and State, on
conditions which, whilst distinguishing civil life from religious life,
shall guarantee to individuals religious liberty in civil society, and to
the church itself its internal autonomy in matters of faith and of
religious discipline. The other solution is the complete separation of
Church and State, and their mutual independence.

That the Church prefers the system of an Alliance with the State to
that of the Church's Liberty and isolation from the State, I well
understand.

She is right. Alliance with the State is to her a sign of strength, a


means of influence, a pledge for her dignity and her stability. The
complete separation of the two societies leaves religious
institutions, and particularly their clergy, in a fluctuating and
precarious situation: a system essentially democratic, it rather
places the ecclesiastical magistracy under the opinions and wills of
its lay members, than these under the influence of the religious
authorities. This system is especially alien to the origin, the
fundamental principle, and the Hierarchy, of the Roman Catholic
Church; it is impossible for this Church to accept it unless urgently
demanded by the interests of moral authority, independence, and
liberty. But let not the Roman Catholic Church misapprehend; an
alliance of Church with State has also conditions without which a
Church would vainly expect any advantage; for the alliance to be
serious and effectual, there must be between Church and State a
large measure of harmony as to the essential principles of the
religious society and of the civil society which the Church and the
State respectively represent: if the two societies and those who
govern them, do not mutually admit their respective principles, if
they disavow each other incessantly, and carry on in the bosom of
their alliance, a war, open or secret, all the good effect of such
alliance disappears, and the alliance itself is soon compromised.
The treaties concluded at different epochs, under the name of
Concordats, between Chambers and States in different countries of
Christendom, have only been possible and efficacious, because
there was a great basis of harmony in the fundamental institutions
of the two contracting parties; they differed upon some points; they
had reciprocally to make concessions and grant guarantees; but
taken altogether they approved of each other and were sincere in
supporting each other; peace was the point from which their
alliance started, and the dissentiments which existed on each side
had no reference to any vital questions. It suffices for us to cast a
glance at the history of Catholicism in France, of the Anglican
Church in England, of the Lutheran Church in Germany and in
Sweden, to acknowledge this truth; and what is occurring and
forming matter of negotiation in our days in Italy and in Austria,
upon the subject of the relations of the Church with the State,
furnishes a further striking confirmation. In an age of liberty, of
publicity, and of continual discussion, when it is possible for
anything to be thought or said, and for any opinion to be
maintained or attacked, it is more than ever indispensable that any
treaty between Church and State should be serious and sincere;
that is to say, that the two contracting parties should recognise and
accept in each other, without equivocation and without subterfuge,
the character which each really possesses. This is the only
condition upon which an alliance can be real, becoming, and
advantageous. In presence of the undisguised movements and the
ever recurring and daring ventures of Liberty, a policy of reticence
and procrastination, obscure and dim reservations, inconsistent
expedients, and secret warfare, is no longer practicable; such
policy, far from lending any help, discredits and weakens the power
which places its trust in it. As for me, I believe that the Catholic
Church, if not without endangering her habits, at least without
endangering her essential principles, has it in her power to set
herself at peace with the fundamental principles of modern society
and of actual civil governments; but should she either not wish or
not know how to march towards this object and to obtain it, let her
not give way to any illusion; alliance with the State would be rather
a source of weakness and of peril to her than an advantage, and
she would only eventually be driven to seek a refuge in the system
of separation and complete independence.

As for the State, the system which separates the two societies
would free it from many a burthen and much embarrassment; but
it would cause her other embarrassments, and lead to the loss of
many advantages. It is convenient to discourse of the principle of a
"Free church in a free country," but after the long alliance which
has existed between them, it is easier to proclaim such principle
than to apply it: not only is it impossible to divorce Church from
State without violently wrenching asunder previous bonds, but
more lasting consequences ensue; once disengaged from every
connection with the civil power, ministers of religion busy
themselves no longer about the interests of civil society; their
thoughts are exclusively absorbed by questions of religion and its
affairs. Governments have long been accustomed to derive, and
derive at the present day, a moral influence of great value from an
alliance with the Church: but this influence supposes one condition
which is not only especially important in our days, but of capital
importance: in the actual state of opinion and of manners, no good
results can be politically looked for from the alliance, if the civil
power do not abstain from all interference in questions purely
religious; the complete independence of the church and of its
chiefs, in matters of faith and of religious discipline, is the only
condition which can justify their giving their indirect support to the
state government, and which can purge their support of all impure
motives. The alliance of the two powers could formerly, in a certain
degree, co-exist with no inconsiderable confusion in their respective
attributes, and a somewhat earnest claim on the part of each to
domineer over the other; nothing similar can occur at the present
day; neither Church nor State can any longer be the master or the
servant of the other. Let neither princes nor priests deceive
themselves; their reciprocal independence, and their uncontested
empire, each in its own province, can alone give to their alliance
the dignity which the alliance requires, if it is to be real, efficacious,
and lasting.

Every road leads me to the same point; to every question the facts
give me the same answer. Liberty has need of Christianity,
Christianity has need of Liberty. As modern society demands to be
free, the religion of Christ is its most necessary ally. Christianity and
civil society have mutually, I admit it, a grave feeling of disquietude
and distrust; but this disquietude and distrust are not natural and
inevitable results of principles essential to civil society and religious
society, of any compulsory relations existing between them; they
spring from the faults which the two institutions have committed
towards each other, and from the contest which each has forced
upon the other. Liberty alone can effectually combat such
sentiments which have become habitual and traditional. To dissipate
them entirely, something besides Liberty is requisite; but without
Liberty neither religious society nor civil society will obtain their
legitimate objects, these objects being peace in their relations to
each other, and the moral progress of man, and of the State,
whether allied with or independent of the Church.
Second Meditation.

Christianity And Morality.

Two attempts are now being simultaneously made, of different


characters, although, of the same origin and tendency. Seriously
minded men, who persist in believing and calling themselves
Christians, are labouring to separate Christian morals from Christian
dogmas, and although they make Jesus their moral idea of
humanity, are stripping him of his miracles and divinity. Others, who
declare openly that they are no Christians, endeavour to separate
morality in the abstract from religion in the abstract, and place the
source of morality, as well as its authority, in human nature, and in
it alone. On the one side we find a Christian morality independent
of Christian faith; on the other a Morality independent of all
religious belief, either natural or revealed: these two doctrines are
in our days proclaimed and propagated with ardour.

I frankly admit that their defenders are sincere in adopting and


upholding them, and that they do so in the name of truth alone. In
philosophy, as in politics, I believe error and honest intentions to be
more general than falsehood and evil design. Moreover, who would
discuss convictions, unless himself convinced that they are serious
and earnest? Opinions founded on interested or hypocritical motives
are not worth the honour of a discussion; they merit only to be
attacked and unmasked. In the name of truth alone I combat the
two doctrines to which I have alluded, and which some now strive
to accredit.

The true cause of this twofold attempt is the incredulity and the
scepticism which prevail with regard to religion. Non-Christians are
numerous; few Deists are quite sure of their belief and of its
efficacy. A necessity for morality is felt to exist; its right to regulate
the actions of man is acknowledged; it is in order to preserve to it
its integrity and its force that efforts are made to separate it from
religion, from all religious creeds, all of which, it is here assumed,
are either ruined or tottering. Thus, Independent Morality is, as it
were, a raft, offered to the human soul, and to human society, to
save their time-worn vessel from being wrecked.

The idea is false, the attempt of evil consequence. They who flatter
themselves that they can leave Christian morality standing, after
wrenching it from Christian dogmas,—and they who believe it
possible to preserve morality, after detaching it from religion,—err
alike, for they fail to recognise the essential facts of human nature
and of human society.

Both doctrines are derived from an inexact and incomplete


observation of these facts. I have already stated in these
Meditations what I think of the isolation of Christian morality from
Christianity, and the reason why I reject it. At present I apply
myself to the idea of independent morality, and in the name of a
psychology, pure at once and severe, I affirm that there exists an
intimate, legitimate, and necessary union between morality and
religion.

A preliminary observation occurs to me. Those who adopt the


theory of an independent morality, start from the idea that there is
a moral law, strange to and superior to all interested motives, to all
selfish passions; these rank duty above, and treat it as independent
of, every other motive of action.

I am far from contesting this principle with them, but they forget
that it has been, and still is, strongly contested: contested by both
ancient and modern philosophers. Some have considered the
pursuit of happiness, and the satisfaction of individual interests, as
the right and legitimate aims of human life. Others have placed the
rule of man's conduct, not in personal interests, but in general
utility, in the common welfare of all mankind. Others have thought
that they could perceive the origin and the guarantee for morals in
the sympathy of human sentiments. The moral and obligatory law,
or duty, is far from being the recognised and generally accepted
basis of morality; systems the most varied have arisen, and are
incessantly forming themselves, with respect to the principles of
morals, as with respect to other great questions of our nature; and
the human understanding fluctuates no less in this corner of the
philosophic arena than in the others. Let the moralists of the new
school not deceive themselves; in proclaiming morality to be
independent of religion, they mean to give it one fixed basis, the
same for all, and they believe that they succeed in the attempt.
They deceive themselves: morality, thus isolated, remains as much
as ever a prey to the disputes of man.

I pass over this grave misconception on the part of the defenders


of the system, and I examine the system itself. Let us see if it is
the faithful and full expression of human morality, if it contains all
the facts which constitute its natural and essential elements.

These facts I sum up as follows: the distinction between moral


good and evil; the obligation of doing good and avoiding evil; the
faculty of accomplishing or not this obligation. In brief and
philosophic terms the Moral Law, Duty, and Liberty. These are the
natural, primitive, and universal facts which constitute human
morality; it is by reason and by virtue of these facts that man is a
moral being.

I have not here to enter into a discussion of these same facts; I do


not occupy myself at this moment with systems which disregard or
deny them, in whole or in part; all the three facts, or any one of
the three. The partisans of the system of independent morality
admit them all, as I do; the question between them and myself is
this, whether or not, whilst rendering homage to the true principle
of morality, they fully comprehend its signification, and accept its
results.

It is the characteristic and the honour of man that he is not


satisfied with merely gathering facts which relate either to himself
or to the external world, but that he seeks to know their origin and
object, their import and bearing.

In morals, as in physics, statistics are only the point from which


science sets out; it is only after having well observed facts, and
having verified them, that we have to discuss the questions which
they raise, and the further ultimate facts which the facts already
ascertained contain and reveal. The fact of human morality, such as
I have just described it in its three constituent elements, the Moral
Law, Duty, and Liberty, cannot fail to suggest these two questions:
Whence proceeds the moral law, and whence is its authority? What
is the sense, and what the ultimate result to the moral being
himself, of the fulfilment or violation of his duty; that is to say, of
the use which he makes of his liberty? No philosophical system can
either suppress or elude these questions; they present themselves
to the mind of man as soon as he directs his attention to the moral
character of man's nature. I propose to consider in succession the
three constituent elements of this great truth, so as to determine
rightly its source and bearing.

Moral law has neither been invented by man, nor does it spring
from any human convention; man, by acknowledging it, admits that
he has not created it, that he cannot abolish or change it. Political
and civil laws are diverse and ever varying; they depend in a great
measure upon time, place, social circumstances, or human will;
when men adopt or reject them, they do so with the feeling that
they are the masters of them, to deal with them accordingly as
their interests or their fancies suggest.

But when a law presents itself to them in the form of a moral law,
they feel that this is not dependent on them, that it takes its source
and derives its authority elsewhere than from their own opinion or
volition. They may mistake in rendering or in refusing homage to a
particular precept of conduct; they may attach to laws a moral
value which they do not intrinsically possess, or pass unnoticed the
really moral character of another law, and the obligations which it
imposes upon them; but wherever they believe that they perceive
the character of a moral law, they bow before it as before
something which does not emanate from them, and before a power
of a different nature from man's.

The moral law no more belongs to the general mechanism of the


world, than to the invention of man; it has none of the
characteristics that mark the laws of physical order; none of the
results which follow from them; it is by no means inherent in the
forms or combinations of matter; it does not govern the relations or
movements of bodies; obligatory, and fixed as fate, it addresses
itself solely to that intelligent and free being, of whom Pascal said,
in his grand language, "If the universe were to crush him, still man
would be more noble than that which destroyed him, because he
knows that he dies; and of the advantage that the universe has
over him, the universe knows nothing." Man does much more than
know that he dies; it happens, sometimes, that he encounters
death voluntarily—that he chooses to die in obedience to the moral
law. It is the law of Liberty.

What mean these words, Law of Liberty? How does this law, called
Duty, come to establish itself in the human mind, and command
man's Liberty to respect it?

Some essay to found Duty upon Right, and to derive its authority
solely from the independence and dignity of humanity. Man, it is
said, feels and knows that he is a free agent; as such it is his right
that no human being shall attack his independence or his dignity.
He finds in every other human being the same nature, and
therefore the same right as he possesses himself. Thus mutual right
is derived from individual right, and "Duty is nothing but the right
which it is recognised that another possesses." [Footnote 14]

[Footnote 14: La Morale Independante, a weekly journal,


No. 1, 6th August, 1865.]

There is here a profound mistake, and a strange forgetfulness.

Why, when a man finds himself in relation with his fellow-men,


does he attribute to them the same right which he recognises
himself as possessing, and which he calls upon them to see and
admit there? If this is a prudent calculation, the wisdom which
arises from a correct appreciation of his interest, let us have done
with it, it is not morality. If, prudence and interest apart, man
regards himself as bound to pay, to the independence and personal
dignity of his fellow-men, the same respect, and to attribute to
them the same right, as he lays claim to for himself; if reciprocity
becomes in this manner the fundamental principle of morality, what
becomes of the obligation where there is no reciprocity? Will man
be bound to respect in others the right which will not be respected
in himself? If he is bound to it in all cases, and in spite of
everything, then Duty has another source than the mutual respect
of persons. If he is, on the other hand, not bound to it in all cases,
what becomes of the paramount and absolute character of Duty; in
other words, of the moral law? It is no longer anything but law
upon condition.

Not merely the religion of Christ, but all the great doctrines of the
world, religious or philosophical, peremptorily refuse to attach this
conditional character of reciprocity to the moral law; all maintain
that duty is in every case absolute and imperative, independently of
the conduct of others. "If ye love them which love you, what thank
have ye? for sinners also love those that love them. And if ye do
good to them which do good to you, what thank have ye? for
sinners also do even the same." "Love ye your enemies, and do
good, and lend, hoping for nothing again; and your reward shall be
great, and ye shall be the children of the Highest: for he is kind
unto the unthankful and to the evil." [Footnote 15]

[Footnote 15: Luke vi. 32, 33, 35.]

"Be ye," say the laws of Menou to the Hindoos, "as the wood of
the sandal tree, that perfumes the hatchet which wounds it." If we
interrogate Plato, Aristotle, Zeno, Kant; in whatever other respect
they may disagree, they think upon this fundamental point with the
Gospel and the Laws of Menou.

It is in the confusion of Duty and of Right, and in the inversion of


their natural and their true order, that the error resides of those
who maintain the Theory of an Independent Morality. Duty is the
moral law of men's actions; law intimate, personal. Right, on the
other hand, is derived from the application of the moral law to the
relations of men. I will not deny myself the great yet melancholy
pleasure of citing upon this subject a few words of a person whose
mind and life were united to mine, and who, in a modest essay,
threw over this important subject a flood of light as vivid as it is
pure: "The word Right, brings with it the idea of a relation to
something. As every Right is an application of a moral law to the
different relations of Society, there exists not a Right of which
Society is not the occasion. A Right is only the moral power of an
individual over the Liberty of another: a power attributed to him by
virtue of the moral law which regulates the relations of men with
one another. Duty is the sole basis of Right. Did there exist no
duties there would exist no rights. There is no claim of a right
which does not affirm a Duty to be its source. Duty applied as a
rule to govern the relations of man to man constitutes justice;
justice cannot exist without Duty; a thing is neither just, nor unjust,
as far as regards the being who has not had the duty prescribed to
him of distinguishing between them. Ideas of Right are as essential
to men as ideas of duty; for if the idea of Duty is the social bond;
—the means of peace and of Union amongst mankind;—the idea of
Right constitutes the arms, offensive and defensive, which society
gives to men, for reciprocal use. Every man has a consciousness of
his own rights, which aids him to keep others in the line of their
duty; but rights only so far aid him to do this, as the duty upon
which they are founded is known and respected; for with regard to
that man who ignores his duty, the man who has a right has
absolutely nothing. Right is a moral power producing its effects
without the help of physical force; if he who has both right and
power must employ the power to enforce his right, it is no longer
his right which triumphs, it is his power; his right remains to him to
justify the employment of force; but it is not his right which has
made his cause triumph. Thus it is that the idea of Duty is the
basis of society, and is at the same time the basis of the idea of
right, an idea which in its turn contributes also to the stability of
society. To found society upon the sole idea of duty, is to deprive
society of one of its most powerful means of defence and of
development; to strip the tree of the buds which serve to give it at
once strength and amplitude. To found society upon the idea of
Right without the idea of duty, is to cut away the very roots of the
tree." [Footnote 16]

[Footnote 16: "Essai sur les idées de droit et de devoir


considérées comme fondement de la société." It is
inserted in the work entitled, "Conseils de Morale, ou
Essais sur l'homme, les mœurs, les caractères, le
monde, les femmes, l'education, etc. Par Madame
Guizot, née de Meulan," (2 vols. 8vo, 1828) vol. ii., pp.
147-271.]

This is not all. Besides the mistake which they commit in


considering Duty as a mere consequence of Right, derived from the
independence and dignity of man as man, the advocates of the
theory of an independent morality forget an entire class of moral
elements occupying an important position in our nature; I mean,
the instinctive sentiments intimately allied to the Moral Law,
sentiments to which the notion of a Right, founded upon the
independence and dignity of man's personality, is completely
strange. Is it on account of the independence and dignity of man's
personality that fathers and mothers regard it as their duty to love
their children, to take charge of them, to work for and devote
themselves to them? Is it by virtue of this principle, and of the
right which flows from it, that children are bound to honour their
father and their mother? Man's soul, man's existence, is full of
moral relations and moral acts, in which the idea of Right has no
part; no part, I mean, in the sense which these theorists of an
independent morality attach to it: their system is no more an
explanation of Sympathy than of Duty.

I am touching upon the source of their error. If they make the


principle of human morality consist in a Right emanating from
man's Liberty and man's intelligence, it is that they see in man only
a free and intelligent being. Strange ignorance, and mutilation of
man's nature. At the same time that he is a free and intelligent
being, man is a being dependent and subject: he is dependent, in
the material order, upon a power superior to his own; and subject,
in the moral order, to a law which he did not make, which he
cannot change, which he is forced to admit even whilst he is free
not to obey it; a law from which he cannot withdraw himself
without troubling his soul and endangering his future. Morality in a
sense is in effect independent; it is essentially independent of man;
man, the free agent man, is its subject. Morality is truly the law of
Liberty of Action.

Liberty is not an isolated fact, which exhausts itself by working its


own completion, and which, once accomplished, remains without
further consequences. To Liberty is attached Responsibility. When
the human being, giving effect to his free will, resolves and acts, he
feels that he is responsible for his resolution and his act. The Laws
of Society declare this to him in express terms, for they punish him
if they judge his act to be criminal; not merely because they find
his act to be hurtful, but because they find it to be morally
culpable: for, were its author pronounced to be mad, or his mind or
volition recognised as unsound, the laws of society would acquit
him. And if a culprit escape legal punishment, he does not escape
from the internal punishment of remorse. Without speaking of
penal laws, remorse is at once the proof and the sanction of moral
responsibility. Possible it is that all remorse may be lulled to sleep
in the mind of the hardened offender; but there are a thousand
instances to prove that it may be always reawakened. Neither in
good nor in evil is man's nature entirely effaced. Repentance
sometimes hides itself in recesses so profound, that to penetrate
thither is impossible, except for the soul which feels repentance
even when seeking to escape from it.

As Liberty supposes responsibility, so Responsibility supposes an


idea of merit or of demerit attaching naturally to the use made of
liberty. I set aside here all the questions, in my opinion, ill put and
wrongly solved by Theologians, upon this subject of merit or
demerit. According to the general sentiment and common sense of
all mankind, there is merit for a man in the accomplishment of
Moral Law, there is demerit in its violation. It is a fact recognised
and proclaimed even in the simplest and most ordinary incidents of
human life, as well as in the political organisation of society, and in
the problems which concern the eternal future. However the
recompense or the punishment may be accelerated or delayed;
whatever its nature or its measure; the moral career of a man is
not complete, nor the moral order established, until the
responsibility inherent in his Liberty has received its complement
and arrived at its end in the just appreciation and equitable return
made to him for his merits or demerits.

Thus far I have spoken of Independent Morality; I have


scrupulously confined myself to studying moral facts as man's
nature, and man's nature alone, presents them to us. I have
considered and described them as they are in themselves, entirely
apart from every other element and every other consideration.
Those moral facts are briefly as follows:—
The distinction between moral good and moral evil.

The Moral Law, the duty of doing good and avoiding evil.

Moral Liberty.

Moral Responsibility.

Moral merit and demerit.

These are, I admit, facts which man recognises in himself as the


proper and intimate characteristics of his own nature. But these
truths once recognised and determined, what is their import? Are
they facts isolated in human nature, as they are in Psychology, or
have they anterior causes and necessary consequences! Are they
self-sufficing, or do they contain and reveal other truths which form
their complement and their sanction? The human mind cannot
elude this question.

I have established that the moral law is not of human invention;


that it does not exist merely by man's agreement; that it is not one
of those laws of fate by which the material world is governed. It is
the law of the intellectual world, of the free world; a law superior
to that world which, by recognising it as law, recognises itself at
the same time both as free and subject. Who is the author of that
law? Who imposes it upon man—upon man of whom it is not the
work, and whom it governs without enslaving? Who placed it above
this world where the present life is passed? Evidently there must be
a superior power from which the moral law emanates, and of which
it is a revelation. With the good sense which his frivolity and his
cynicism made him so oft forget, Voltaire said, speaking of the
material world and the order reigning in it:—

"Je ne puis songer


Que cette horloge existe et n'ait point d'horloger."
I cannot think
This clock exists and never had a maker.

In the moral world we have to do with something far different from


a clock; nor are we in the presence of a machine constructed,
regulated, once for all; the law of Order, that is to say, the moral
law, is incessantly in contact with man's free agency; man does
homage to the law which he is yet at liberty to accomplish or to
violate; the law is a manifestation of the supreme legislator, of
whose thought and will it is the expression. God moral sovereign,
and man free subject, are both contained in the fact of the moral
law. In this fact alone Kant found God; he erred in not also finding
God elsewhere; but it is nevertheless true that it is in the moral
law, the rule of human Liberty, that God shows himself to man
most directly, most clearly, most undeniably.

Just as the moral law, without a sovereign legislator to impose it


upon man, is an incomplete and inexplicable fact, a river without
source, just so the moral responsibility of the free agent man,
without a supreme judge to apply it, is an incomplete and
inexplicable fact, a source without outlet, which runs and loses
itself no one can tell whither. Just as the moral law reveals the
moral legislator, just so does moral Responsibility reveal the moral
judge. Just as the moral law is no law of human invention, just so
human judgments, rendered in the name of moral responsibility,
are hardly ever the judgments perfectly true and just which such
responsibility expects and calls for. God is contained in the moral
law as its primal author, and in moral responsibility as its definitive
judge. The moral system, that is, the empire of the moral law, is
incomprehensible and impossible if there is no God there, not only
to establish it in a region above and paramount to man's free
agency, but to establish it when troubled by man's conduct as a
free agent.

Thus the moral truths, inherent in and proper to the human nature
—that is, the distinction between moral good and moral evil, moral
obligation, moral responsibility, moral merit and demerit,—are
necessarily and intimately connected with the truths of Religion; for
instance, with God moral legislator, God moral spectator, God moral
judge. Thus morality is naturally and essentially connected with
religion. Morality is, it is true, a thing special and distinct in the
ensemble of man's nature and of man's life, but it is in no respect
independent of the ensemble to which it belongs. It has its
particular place in that ensemble, but it is only in that ensemble
that its existence is reasonable, thence only that it derives its
source and its authority.

Morals may, in the order of science, be separately observed and


described; but in the order of actuality morality is inseparable from
Religion.

What would be said of a physiologist if he maintained that the


heart is independent of the brain, because those two organs are
distinct, organs which are closely united and indispensable to each
other in the unity of the human being?

The spectacle of the world leads us to the same result as the study
of man, and reads us the same lesson. History confirms Psychology.
What is the great action which makes itself most remarkable upon
the stage of human societies? The constant struggle of good with
evil, of just with unjust. In this struggle what shocking disorders!
What iniquity perpetrated! How frequent an interregnum in the
empire of the moral law and of justice, and what vicissitudes there!
At one time the moral decree is expected in vain, and the human
conscience remains painfully troubled by the successes of vice and
of crime: at another time, contrary to all expectation, and after the
most deplorable infractions of the moral law, the moral judgment
comes. "In vain," said Chateaubriand fifty years ago, "does Nero
prosper; Tacitus already lives in the empire; he grows up unnoticed
near the ashes of Germanicus, and already a just providence has
left in the hands of an obscure child the fame of the master of the
world." Chateaubriand was right: Tacitus was the avenger of the
moral law outraged by the masters of the Roman Empire; he was
the judge of their triumphs; but in that very Empire the most
victorious of its masters, Marcus Aurelius, after having consecrated
his life to the search after and the practice of the moral law, dies in
profound sadness beneath his tent on the banks of the Danube;
sad on account of his wife, sad on account of his son, and of the
future of that world which he had governed, and which was only to
be renewed, and regenerated, by those Christians whom he had
persecuted. Everything is incomplete, imperfect, incoherent,
obscure, contradictory, in this vast conflict of men and actions
called History; and Providence, the personification of eternal
wisdom and justice, sometimes manifests itself there with éclat,
and sometimes remains there, inert and veiled, beneath the most
sombre mysteries. Is such the normal, definitive state of the
universe? Shall truth, shall justice, never assume there more space
than they now occupy? When shall light dawn upon the darkness?
Who restore order to this chaos? Man evidently is insufficient to the
task; in the world, as in individual man, the moral principle is still
mutilated, and too infirm for its mission, unless it is intimately
united to the religious principle. Morality can as little dispense with
God in the life of the human race, as in that of the individual man.

In these days more than ever morality has need of God. I am far
from thinking ill of my country or of my age; I believe that they
progress, that they have a future; but humanity is now-a-days
exposed to a rude trial. On one side we have been witnesses to
events of the most contradictory character: everything in the world
of opinion has been questioned; everything in that of facts has
been shaken, overthrown, raised up again, left tottering. Oppressed
by this spectacle, what remains to men's minds more than feeble
convictions—dim hopes? On the other side, in the midst of this
universal shock of minds, science, and man's power over the
surrounding world, have been prodigiously extended and confirmed;
light has shone more and more brightly upon the material world, at
the very moment when it was becoming paler and paler, declining
more and more, in the moral world. We have plucked and are still
plucking, more actively than ever, the fruit of the tree of
knowledge; whereas the rules of human conduct, the laws of good
and of evil, have become indistinct in our thought. Man remains
divided between pride and doubt; intoxicated by his power, and
disquieted by his weakness. Man's soul, how perturbed! human
morality, how endangered!

Thus far I have treated the subject with far more reserve and
indulgence for the opinions of others than I intended. I have
limited myself to the bounds assigned to the question by the
advocates of the theory of independent morality themselves. I have
done nothing more than set in broad daylight the intimate, natural,
and necessary connection of morals with religion; of man, moral
being, with God, moral sovereign. I am only at the threshold of the
truth. It is not merely to religion in general that morality pertains; it
is not merely the idea of God of which it has need; it requires the
constant presence of God, his unceasing action upon the human
soul. It is from Christianity alone that morality can now derive the
clearness, force, and security, indispensable for the exercise of its
empire. And it is not for her practical utility, it is for her truth, her
intrinsic value, that I hold Christianity to be necessary to the
human soul, and to human societies. It is because she is in perfect
harmony with man's moral nature; and because she has been
already tested in man's history; that Christianity is the faithful
expression of the moral law, and the legitimate master of the moral
being.

The first and the incomparable characteristic of Christianity, is the


extent, I should rather say the immensity, of her moral ambition.
The moral system established by Christ has often been contrasted
with the reforms aimed at by great men whose endeavour it also
was to fix moral laws for man's conduct, and to secure their empire
over him. Jesus has been compared to Confucius, Zoroaster,
Socrates, Cakia-mouni, Mahomet. The comparison is singularly
inappropriate and superficial. The wisest, the most illustrious, of
these moral reformers, even the most powerful, understood and
accomplished at best but a very limited and incomplete work;
sometimes they only sought to place in a clear light the rational
principles of morality; sometimes they gave to their disciples,
addressing themselves to these alone, rules for conduct in
conformity with rational principles of morality; they taught a
doctrine or established rules for discipline; they founded schools or
sects. The Christian work was something quite different. Jesus was
not a philosopher who entered into discussions with his disciples,
and instructed them in moral science; nor a chief who grouped
around him a certain number of adepts, and subjected them to
certain special rules which distinguish, nay sever, them from the
mass of mankind: Jesus expounds no doctrine, sets up no system
of discipline, and organises no particular society: he penetrates to
the bottom of the human soul, of every soul; he lays bare the
moral disease of humanity, and of every man; and he commands
his disciples with authority to apply the cure, first to themselves,
and then to all men:—"Save your soul, for what would it profit a
man to gain the whole world, if he lose his own soul?" "Go and
preach to all nations."

What philosopher, what reformer, ever conceived an idea so


ambitious, so vast? ever undertook to solve so completely, so
universally, the moral problem of man's nature and man's destiny?

And this was no chimerical ambition; the mission of Christ has been
pursued, and is still being pursued in the world, its onward
movement often crossed, interrupted, altered, never hopelessly
arrested. And during the first three centuries of Christianity, it was
in the name and solely with the arms of Faith and of Liberty, that
she commenced her enterprise of vanquishing man and the world.
And in these days, after the lapse of nineteen centuries, in spite of
the intermixture of error, of crime, and evil, it is with the same
arms, and with them alone, that Christianity, in the name of Faith
and of Liberty, and exposed to fresh and violent attacks, resumes in
the moral world the same task, and promises herself fresh success.
Without attempting, indeed, to sound them to their depths, let me
at least indicate the causes of this indomitable vitality of the
Christian Religion, and show why the hope is well founded which
she entertains in the midst of her trials.

Of the moral philosophers, almost all are either bitter censors, cold
observers, or flatterers of human nature. Some of them proclaim
that man is naturally good, and that his vices are solely due to the
bad institutions of society. Some, again, regard self-interest and
self-esteem as the only springs of human actions. Others describe
the errors and foibles of man with a careful sagacity, and yet a
sagacity that does not indispose them to jeer and mock at them, as
if they were actors in a drama, both amused themselves and
amusing the spectators. How different the regard and the
sentiment of Jesus when contemplating man: how serious that
regard! how profound, how pregnant with effect that sentiment! No
illusion, no indifference with respect to the nature of man; full, he
knows it to be, of evil and at the same time of good; inclined to
revolt against the moral law, at the same time that it is not
incapable of obeying it; he sees in man the original sin, source of
the troubles and of the perils of his soul: he does not regard the
evil as incurable; he contemplates it with an emotion at once
severe and tender, and he attacks it with a resolution superior to
every discouragement, and prepared for every sacrifice. Why should
I not simply employ Christian terms, the most genuine of any, as
well as the most impressive? Jesus lays bare the sin without
reserve, and without reserve devotes himself to the sinner's
salvation. What philosopher ever comprehended man so well, and
loved him so well, even whilst judging him so freely and so
austerely?

Jesus does not occupy himself less with man's futurity than with
man's nature. At the same time that he lays down, in all its rigour,
the principle of the moral law, the pure accomplishment of duty, he
forgets not that man has need of happiness, and thirsts after
happiness, after a happiness pure and lasting; he opens to virtue
the prospect of its attainment, he holds out a hope, foreign to all
worldly objects, hope of an ideal happiness inaccessible to the
curiosity of man's mind, but apt to satisfy the aspirations of his
soul, and not, as it were, a conquest to be effected by merit, nor
the acquittal of a debt, but a recompense to be accorded to the
virtuous efforts of man by the equitable benevolence of God. The
Christian Religion, at the same time that it compels man during this
life to constant and laborious exertion, has in store for him, if only
he labour in accordance to the law, "the kingdom of God" and "the
promises of eternal life."

Thus, Jesus knows human nature entirely, and satisfies it; he keeps
simultaneously in view man's duties and his necessities, his
weaknesses and his merits. He does not allow the curtain to fall
upon the rude scenes of life, and the sad spectacles of the world,
without any dénouement. He has a prospect, and a futurity, and a
satisfaction for man, superior to his trials, and superior to his
disappointments. In what manner does Jesus attain this result?
How does he touch all the chords of man's soul, and respond to all
its appeals? By the intimate union of morality with religion, of the
moral law with moral responsibility: sole view, complete at once
and definitive, of the nature and destiny of humanity; sole
efficacious solution of the problems which weigh upon the thought
and life of man!

I say the sole efficacious solution. Efficacy is, in truth, the peculiar,
the essential characteristic of Christianity. However high-reaching
the ambition of philosophy is, it is infinitely less so than that of
religion. The ambition of philosophers is purely scientific. They
study, observe, discuss; their labours produce systems, schools.
The Christian Religion is a practical work, not a scientific study. At
the base of its dogmas and of its precepts there is certainly a
philosophy, and, in my opinion, the true philosophy; but this
philosophy is only the point from which Christianity departs, not its
object. The object is to induce the human soul to govern itself
according to the divine law; and to attain this object it deals with
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like