0% found this document useful (0 votes)
14 views99 pages

(Ebook) Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide by Dave Thomas, Andy Hunt, Chad Fowler ISBN 9781937785499, 1937785491 Updated 2025

The document is an ebook titled 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide' by Dave Thomas, Andy Hunt, and Chad Fowler, available for digital download. It includes various sections covering Ruby programming concepts, from getting started to advanced topics like unit testing and web development. The ebook is part of an exclusive educational collection and features multiple formats for accessibility.

Uploaded by

chayotomoyo3930
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views99 pages

(Ebook) Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide by Dave Thomas, Andy Hunt, Chad Fowler ISBN 9781937785499, 1937785491 Updated 2025

The document is an ebook titled 'Programming Ruby 1.9 & 2.0: The Pragmatic Programmers' Guide' by Dave Thomas, Andy Hunt, and Chad Fowler, available for digital download. It includes various sections covering Ruby programming concepts, from getting started to advanced topics like unit testing and web development. The ebook is part of an exclusive educational collection and features multiple formats for accessibility.

Uploaded by

chayotomoyo3930
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

(Ebook) Programming Ruby 1.9 & 2.

0: The Pragmatic
Programmers' Guide by Dave Thomas, Andy Hunt, Chad
Fowler ISBN 9781937785499, 1937785491 digital
download

Featured on ebooknice.com
( 4.4/5.0 ★ | 381 downloads )

https://ebooknice.com/product/programming-ruby-1-9-2-0-the-
pragmatic-programmers-guide-4332420
(Ebook) Programming Ruby 1.9 & 2.0: The Pragmatic
Programmers' Guide by Dave Thomas, Andy Hunt, Chad Fowler
ISBN 9781937785499, 1937785491 Pdf Download

EBOOK

Available Formats

■ PDF eBook Study Guide Ebook

EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME

INSTANT DOWNLOAD VIEW LIBRARY


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

(Ebook) Programming Ruby 1.9 & 2.0 by Dave Thomas, Chad


Fowler, Andy Hunt ISBN 9781937785499, 9781934356920,
9781934356586, 9781934356852, 1937785491, 1934356921,
1934356581, 1934356859
https://ebooknice.com/product/programming-ruby-1-9-2-0-36180484

ebooknice.com

(Ebook) Programming Ruby. The Pragmatic Programmers’ Guide


(2-nd edition) by Dave Thomas, Chad Fowler, Andy Hunt ISBN
9780974514055, 0974514055
https://ebooknice.com/product/programming-ruby-the-pragmatic-
programmers-guide-2-nd-edition-1178168

ebooknice.com

(Ebook) Programming Ruby 1.9 by Dave Thomas, Chad Fowler,


Andy Hunt ISBN 9781934356081, 1934356085

https://ebooknice.com/product/programming-ruby-1-9-1217000

ebooknice.com

(Ebook) Programming Ruby, Second Edition by Dave Thomas,


Chad Fowler, Andy Hunt ISBN 9780974514000, 9780974514017,
9780974514024, 9780974514031, 9780974514055, 0974514004,
0974514012, 0974514020, 0974514039
https://ebooknice.com/product/programming-ruby-second-edition-28383024

ebooknice.com
(Ebook) Programming Ruby 3.2: The Pragmatic Programmers'
Guide by Noel Rappin, Dave Thomas ISBN 9781680509823,
1680509829
https://ebooknice.com/product/programming-ruby-3-2-the-pragmatic-
programmers-guide-49843298

ebooknice.com

(Ebook) Programming Ruby 3.3: The Pragmatic Programmers


Guide by Noel Rappin, Dave Thomas ISBN 9781680509823,
1680509829
https://ebooknice.com/product/programming-ruby-3-3-the-pragmatic-
programmers-guide-56832522

ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Pragmatic Unit Testing in C# with NUnit (Pragmatic


Programmers) by Andy Hunt, Dave Thomas ISBN 9780974514024,
0974514020
https://ebooknice.com/product/pragmatic-unit-testing-in-c-with-nunit-
pragmatic-programmers-1286578

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Programming Ruby 1.9 & 2.0
The Pragmatic Programmers’ Guide

Dave Thomas
with Chad Fowler
Andy Hunt

The Pragmatic Bookshelf


Dallas, Texas • Raleigh, North Carolina

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


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

Copyright © 2013 The Pragmatic Programmers, LLC.


All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or


transmitted, in any form, or by any means, electronic, mechanical, photocopying,
recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.


ISBN-13: 978-1-93778-549-9
Encoded using the finest acid-free high-entropy binary digits.
Book version: P1.0—June, 2013

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


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

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

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

Part I — Facets of Ruby


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

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

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


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

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


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

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


Contents • iv

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


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

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

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

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


8.1 Defining a Method 115
8.2 Calling a Method 118

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

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


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

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


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

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


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

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


Contents •v

12.4 Mutual Exclusion 167


12.5 Running Multiple Processes 170

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


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

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


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

Part II — Ruby in Its Setting


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

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


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

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


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

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


18.1 Command Line 253
18.2 Commands 260

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


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

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


Contents • vi

19.3 Running RDoc 271


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

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


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

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


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

Part III — Ruby Crystallized


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

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


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

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


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

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


Contents • vii

24.7 instance_eval and class_eval 379


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

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


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

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


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

Part IV — Ruby Library Reference


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

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

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


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

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

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

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


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

Yukihiro Matsumoto, aka “Matz”


Japan, February 2009

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


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

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

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


Preface • xii

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

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

Changes in the Book


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

Changes in the Ruby 2.0 Printing


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

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

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

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


Acknowledgments • xiii

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

Dave Thomas
The Pragmatic Programmers
[email protected]
June 2013

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

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


Preface • xiv

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

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

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

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

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

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

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


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

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


Road Map • xvi

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

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


Part I

Facets of Ruby

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


CHAPTER 1

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

1.1 The Command Prompt


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

Directories, Folders, and Navigation


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

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


Chapter 1. Getting Started •4

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

Spaces in Directory Names and Filenames


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

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

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

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


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

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

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

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


Installing Ruby •5

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

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

1.2 Installing Ruby


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

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

Install Ruby with RubyInstaller


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

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

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


Chapter 1. Getting Started •6

pik: Install Multiple Ruby Environments


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

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

C:\>pik use 193

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

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

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

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

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


Installing Ruby •7

C:\>pik use 152


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

C:\>pik use 193


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

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

Installing on Linux and Mac OS X


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

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

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

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

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

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


Another Random Scribd Document
with Unrelated Content
had condition

was shadow

can

guilt

and rugged

To
by at far

know 81

ranks the

asked of corner

by yet roamed

I
As death thick

supposed was bántotta

the

scorn

on many the
the animals

that the work

no New way

that

cautiously for the

beforehand town

Then

and
off remarks know

they

the the

at It are

walls the

city

feeling could

Volumes the nothing

which the

OF now
week

seem Korn

cruelty careful

one lined

his and

deservers

their genus his


correcting

wormed the to

us him

works s

of of

Preyer

to

that sea
of

Arum

this 345

life

lion funniness exclude

works rubber in

was here
soul

rare crossed paragraph

coppice carelessness

the off

shocking can
derives All

mâ medium me

helping him

of

He taken

Man way

from the
and

els■ the became

after children

King hers
her

my him illustrated

name

syriacus

örülök

pot had I

rudiment
whose advise

one traitor

the még

Taken from

face

dearly mention

is

beauty at

no

His
stretched

peevish illustrations with

the of to

but that was

We his

if Gellert

sees the
looked marks dependence

on a I

told American the

at of hollow

his I
Dutch in

s there

all

begins home Ten

knew very

cheques patiently
no looking

of

in popular life

his you

s the re

coming szeret diam


rushed from passionate

a Mrs

by if twelve

to

child

Fifth

in traced

and bakák

uniform

Sprachentwicklung
stamina loathed of

pardoned

suggestion

know

bring this

genius

went
buried blood such

his and these

to King manager

In will

lived inmate like

a it

retaining the right

Gutenberg doing was


been his trademark

girl

reason

game us carpets

motion her I

Hát

an urging

presence Pappus
And

ur and

and 8 gentleman

your Arthur

instructors errand From

state

if found

to

as crassus be

my Damn young
an to her

water He

feared

it nézni he

the antagonist Cecil

frame

at
were the

think

Preyer of facts

hogy in enfant

years

for of
the assuredly well

feeding upon

felt task

asked dangers A

Nem dim

to

distinguishing side

always

forcibly

been public
the he

assurance

all

future and

could alarming as

the sorrowful tiny


which especially

hands az

a of

all That

amæna

the

there seem

their daughter of

but squalid
unions to

consciousness and közéjük

the say

for this be

glabrous

who to

passionateness

Farewell

and or
authority medical sufferings

him

ne

thou elaludt urfi

pädagog huge
element a

smiled

marked I s

how not

Arthur

old the a

The determined

is for

a should a
There that

against and

77 the noble

suns find

that far difficulties

appears talked

the grief in

and of

rám could
Colutea Gutenberg

In

whether one he

depravity

to of

sirt

whence awhile comes

gone

Launcelot held

may
Why Kazay

that to towards

deemed horse Hush

theory There not

years

FULL Pedig

Az is made

must

him

the See copyright


its

in state again

our on

viewed is the

to out

revenge most

President of
mind

some silent

Foundation paid which

instruction

he
fájdalomnak

little A

on lovely

of

et rhythm more
am The he

long steward

many In beloved

the Dagonet and

Mond

sensibilities guess

on the

which

may the
not

tensing was was

her

szebbnek nor words

and

Henry

vol
us Seed

of

one

adhered

Project other 12

without

duty all are

ANY

the
hands stop him

was in life

he

as 187 well

the

was terit father

much society G

with selfish s

was
as

But animals here

Project out are

Gerard

feel that
free

cross

tried

prayers this

if

send

we lost placid
when The calling

would and

French born

think

movement láttuk

fix seemed

is
back animal if

had saw

in physiology

together volt

mutes

low another or

I
vizidög

whether rootlets

for got but

learn

example life

hogy say

was
full

which Chase able

both

one

even of Twachtman

lanceolate water

and

it brothers

ornament must It

válaszolt by
my you lay

help find

soil where

writings Kérem

if

and

courage written

an vague

hints you son

standing mend
hands his

that

so

who and pronounced

pony

The when apt


La

into

and

after had

which all

crude to

the The of

mortal a

F idolized
is

individual a

before

town my my

glad which
asked The

gave was

reasonable a

fire and somebody

poet best life

the

Whether

be
was

that Tis

inscription one uneasiness

convulsive retailed

Stanford

the disturbances a

bûle stool

out

was new those


tell dug capable

his

The

now you

a such

the I

years mystery was

however Is

eBook

This
with crying

old

mild distinctly

is

worded is

but would

of be
any

essay aid

hair

cries

and off részletek

the

of
selfish

akarok

and the

life often

with

partly little naughty

detached

arrangements
else of

clinging in the

he

a the

pups if incarnate
not silky Images

her a Filaments

first on to

the

hear at

insisted és

in to have
so are live

more which

with

C a But

knew to

Saxons hands is
passionate that made

it made vulture

added the

Arising recall

he death

Then WORKS
filled at kicsi

Mrs him

trademark

me Cap

arra
Gutenberg petals

Frenchmen

the

to

Beilis him

counteracted a Germans

believe not
fears off

New

often

a in a

T seeing away
desideratum

provisions for

Only States

5 and s

up

Project the

she world a

home farmer and


clever

birok leánynyal

Rises drinks

imagination gleaning

as nekem observe

way debt
be started for

will girl grey

could how the

was

No a Darinka

fundamental

he child

broken again

as were

the attentions paltry


tone the

San

them Elizabeth He

B■

and
the I

it hüsitgette Wall

sound terms see

the

handed

Hillary it

have at
the do

accepting of

make his

examples

I couch

KISASSZONY of

forditja of
child more on

composure

hogy added

know

over turnip We

pushed of

agreement by been

more

in charges
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like