Download ebooks file Programming Ruby 1 9 3rd Edition Dave Thomas all chapters
Download ebooks file Programming Ruby 1 9 3rd Edition Dave Thomas all chapters
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
Random documents with unrelated
content Scribd suggests to you:
mouth, and the beautiful broad brow drooping with the weight of
thought, and yet with an eternal youth and freshness shining out of it
as from the morning forehead of a boy, are all remarkable, and their
harmony with each other in a placid tenderness not less so.
Mr. Lowell, in illustration, read from the “Man of Law’s Tale,” and
other of the poems.
VI
Chaucer had been in his grave one hundred and fifty years before
England had secreted choice material enough to produce another
great poet. Or, perhaps, we take it for granted that Nature
understands her own business too well to make such productions
cheap. Beauty, we know, has no charm like that of its eternal
unexpectedness, and the best delight is that which blossoms from a
stem of bare and long days.
Or is it that the spirit of man, of every race of men, has its fatal ebbs
and floods, its oscillations between the fluid ideal and the solid
matter-of-fact, so that the doubtful line of shore between is in one
generation a hard sandy actuality, with only such resemblances of
beauty as a dead sea-moss here and there, and in the next is
whelmed with those graceful curves of ever-gaining, ever-receding
foam, and that dance of joyous spray which knows not, so bright is it,
whether it be sea or sunshine.
Before the “Faëry Queene,” also, two long poems were printed and
popular—the “Mirror for Magistrates,” and “Albion’s England.” How
the first of these was ever read it is hard to conceive, unless we
accept the theory of some theologians that our earth is only a kind of
penal colony where men are punished for sins committed in some
previous state of existence. The other was the work of one Warner, a
conveyancer, and has a certain philological value now from its
abounding in the popular phrases of the day. It is worth notice, also,
as containing the most perfect example in the English language of
what is called a conceit. It occurs in his account of Queen Elinor’s
treatment of Fair Rosamond:
Which is nonsense and not poetry, though Dr. Percy admired it. Dr.
Donne, and the poets whom Dr. Johnson called metaphysical (as if
all poets are not so), is thought to be full of conceits. But the essence
of a conceit is not in a comparison being far-fetched,—the
imagination can make fire and water friendly when it likes,—but in
playing upon the meanings of two words where one is taken in a
metaphorical sense. This is a mark of the superficial mind always;
whereas Donne’s may be called a subterficial one, which went down
to the roots of thought instead of playing with its blossoms.
Not long after the “Faëry Queene” were published the “Polyolbion” of
Drayton, and the “Civil Wars” of Daniel. Both of these men were
respectable poets (especially Drayton), but neither of them could
reconcile poetry with gazetteering or chronicle-making. They are as
unlike as a declaration in love and a declaration in law.
This was the period of the Saurians in English Poetry, interminable
poems, book after book and canto after canto, like far-stretching
vertebræ, prodigious creatures that rendered the earth unfit for the
dwelling of Man. They are all dead now, the unwieldy monsters—
ichthyo-, plesio-, and megalosauri—they all sleep well, and their
huge remains are found imbedded in those vast morasses, the
“Collections of the Poets.” We wonder at the length of face and
general atra-bilious look that mark the portraits of that generation;
but it is no marvel when even the poetry was such downright hard
work. Poems of this sort might have served to while away the three-
centuried evening of antediluvian lives. It is easy to understand how
our ancestors could achieve great things when they encountered
such hardships for mere amusement. If we agree with Horace in
pitying the pre-Homeric heroes because they were without poets, we
may sincerely commiserate our forefathers of that generation
because they had them. The reading of one of these productions
must have been nearly as long a business as the taking of Troy, and
deserved a poet to sing it. Perhaps fathers, when their time on earth
was up, folded the leaf down and left the task to be finished by their
sons—a dreary inheritance.
Spenser was the pure sense of the Beautiful put into a human body
only that it might have the means of communicating with men. His
own description of Clarion, the butterfly in his “Muiopotmos,” gives,
perhaps, the best possible idea of his own character.
What poet has ever left us such a portrait of himself as this? In that
butterfly Spenser has symbolized the purely poetical nature. It will be
seen that there is no recognition of the moral sense whatever. The
poetic nature considered abstractly craves only beauty and delight—
without any thought beyond—
But how did it happen that this lightsome creature, whose only
business was
should have attempted in his greatest work to mix together two such
incoherent things as sermon and poem? In the first place, the age
out of which a man is born is the mother of his mind, and imprints
her own likeness more or less clearly on the features of her child.
There are two destinies from which no one can escape, his own
idiosyncrasy, and that of the time in which he lives. Or shall we say
that where the brain is in flower of its conceptions, the very air is full
of thought-pollen, or some wandering bee will bring it, we know not
from what far field, to hybridize the fruit?
In Spenser’s time England was just going through the vinous stage
of that Puritanic fermentation which became acetous in Milton, and
putrefactive in the Fifth Monarchy men. Here was one motive. But,
besides this, it is evident that Spenser’s fancy had been colored by
the Romances which were popular in his day; and these had all been
allegorized by the monks, who turned them into prose. The
adventure of the San Grail in the “Morte d’Arthur” reads almost like
an extract from the “Pilgrim’s Progress.” Allegories were the fashion,
and Spenser put one on as he did a ruff, not because it was the most
convenient or becoming thing in the world, but because other people
did.
Spenser has characterized his own poem in the song which the
Sirens sing to Sir Guyon in the twelfth canto of the second book. The
whole passage also may be called his musical as distinguished from
his picturesque style.
In reading Spenser one may see all the great galleries of painting
without stepping over his threshold. Michael Angelo is the only artist
that he will not find there. It may be said of him that he is not a
narrative poet at all, that he tells no stories, but paints them.
I have said that among our poets Spenser stands for the
personification of the poetic sense and temperament. In him the
senses were so sublimed and etherealized, and sympathized so
harmoniously with an intellect of the subtlest quality that, with Dr.
Donne, we “could almost say his body thought.” This benign
introfusion of sense and spirit it is which gives his poetry the charm
of crystalline purity without loss of warmth. He is ideal without being
merely imaginative; he is sensuous without any suggestion of flesh
and blood. He is full of feeling, and yet of such a kind that we can
neither call it mere intellectual perception of what is fair and good
and touching, nor associate it with that throbbing warmth which leads
us to call sensibility by its human name of heart. In the world into
which he carries us there is neither space nor time, and so far it is
purely intellectual, but then it is full of form and color and all earthly
gorgeousness, and so far it is sensual. There are no men and
women in it, and yet it throngs with airy and immortal shapes that
have the likeness of men and women.
And to read him puts one in the condition of reverie—a state of mind
in which one’s thoughts and feelings float motionless as you may
see fishes do in a swift brook, only vibrating their fins enough to keep
themselves from being swept down the current, while their bodies
yield to all its curvings and quiver with the thrills of its fluid and
sinuous delight. It is a luxury beyond luxury itself, for it is not only
dreaming awake, but dreaming without the trouble of doing it
yourself; letting it be done for you, in truth, by the finest dreamer that
ever lived, who has the art of giving you all his own visions through
the medium of music.
VII
Between Spenser and Milton occurred the most truly imaginative
period of English poetry. It is the time of Shakspeare and of the other
dramatists only less than he. It seems to have been the moment in
which the English mind culminated.
It was during this lull, as we may call it, that followed the mighty day
of the Dramatists, that Milton was growing up. He was born in
London on the ninth of December, 1608, and was therefore in his
eighth year when Shakspeare died. His father was of a good family,
which still adhered to the Roman Catholic faith. What is of more
importance, he was disinherited by his father for having adopted
Puritan principles; and he was a excellent musician. Milton was very
early an indefatigable student, even in his twelfth year seldom
leaving his books before midnight. At the university he was
distinguished as a Latin scholar and writer of Latin verses. He was
intended for the Church, but had already formed opinions of his own
which put conformity out of the question. He was by nature an
Independent, and could not, as he says, “subscribe slave.”
Dr. Johnson sneers at Milton for having come home from Italy
because he could not stay abroad while his countrymen were
struggling for their freedom, and then quietly settling down as a
teacher of a few boys for bread. It might, with equal reason, have
been asked of the Doctor why, instead of writing “Taxation no
Tyranny,” he did not volunteer in the war against the rebel American
provinces? Milton sacrificed to the cause he thought holy something
dearer to him than life—the hope of an earthly immortality in a great
poem. He suffered his eyes to be put out for the sake of his country
as deliberately as Scævola thrust his hand into the flame. He gave to
freedom something better than a sword—words that were victories.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookgate.com