Programming Ruby 1 9 3rd Edition Dave Thomas - Download the ebook today and own the complete content
Programming Ruby 1 9 3rd Edition Dave Thomas - Download the ebook today and own the complete content
com
https://ebookgate.com/product/programming-ruby-1-9-3rd-
edition-dave-thomas/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/programming-ruby-the-pragmatic-
programmers-guide-2-nd-edition-dave-thomas/
ebookgate.com
https://ebookgate.com/product/the-well-grounded-rubyist-covering-
ruby-1-9-1st-edition-david-a-black/
ebookgate.com
https://ebookgate.com/product/the-ruby-programming-language-1st-
edition-david-flanagan/
ebookgate.com
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
https://ebookgate.com/product/ios-9-swift-programming-cookbook-first-
edition-nahavandipoor/
ebookgate.com
https://ebookgate.com/product/python-2-1-bible-1st-edition-dave-
brueck/
ebookgate.com
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
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.
ISBN: 1-934356-08-5
ISBN-13: 978-1-934356-08-1
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
4
CONTENTS 5
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
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
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
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
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.
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.
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
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.
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
$
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
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
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.
• 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
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 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
(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.
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
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:
$ 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.
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
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.
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 =.
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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]
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]
"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.
The Moral Law, the duty of doing good and avoiding evil.
Moral Liberty.
Moral Responsibility.
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.
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.
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