Home > Store

Programming Ruby: The Pragmatic Programmer's Guide

Register your product to gain access to bonus material or receive a coupon.

Programming Ruby: The Pragmatic Programmer's Guide

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 2001
  • Dimensions: 7-3/8x9-1/4
  • Pages: 608
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-71089-7
  • ISBN-13: 978-0-201-71089-2

Developers from around the world are using the Ruby language. Here’s what they’re saying about Programming Ruby...

“In their first landmark book, The Pragmatic Programmer, Dave and Andy urged us to learn at least one new programming language every year. It may follow the principle of least surprise that the authors would bring us this year’s candidate, accompanied with a pragmatic philosophy of how to learn your new OO scripting language of choice.”

         —Frank Westphal, independent consultant

“Ruby is an exciting new language, worth knowing about and well worth considering for an upcoming project. It's rare to see such a useful book this early in the life of a new language. But of course I would expect no less from the authors of The Pragmatic Programmer. Andy and Dave: Thanks!”

         —Ron Jeffries, author of Extreme Programming Installed

“I have used Perl and Python for my work... but Ruby just turns my work into fun!”

         —Clemens Hintze, programmer

“Ruby is a remarkably clean, simple, powerful, and practical dynamic OO programming language. Ruby fully deserves this correspondingly best-of-breed book. This book is a ‘must have’ wizard’s workshop for using Ruby to boost your programming power and productivity. This book will greatly amplify the worldwide use of Ruby, stimulate powerful Ruby extensions, and generate demand for second and third editions. I look forward to telling later legions of Ruby users that I was farsighted enough to master Ruby using the classic first edition of Programming Ruby.”

         —Conrad Schneiker

“A good book by a great pair of programmers about a language with a great future. This should be the first Ruby book anyone buys.”

         —Hal Fulton

“Dave and Andy are among the western pioneers who understand the value of this precious gem of a language. They cleaned and polished it well, dazzling us all with its depth and transparency. It's almost magical.”

         —Aleksi Niemelä
Use Ruby and you'll write better code, be more productive, and enjoy programming more.
"I love it. Conceptually it is really clean, and sweet."
--Kent Beck, author of Extreme Programming Explained, on the Ruby language

Ruby is a true object-oriented programming language that makes the craft of programming easier. Ruby is a transparent language: It doesn't obscure your program behind unnecessary syntax or reams of extra support code. Guided by the Principle of Least Surprise, Ruby embodies the values of consistency and simplicity of expression. It's more than a programming language: It's a concise way of expressing ideas. Ruby supports natural intelligence--yours.

Programming Ruby: The Pragmatic Programmer's Guide is your complete Ruby resource. It provides a tutorial and overview of Ruby version 1.6; a detailed description of the language's structure, syntax, and operation; a guide to building applications with Ruby; and a comprehensive library reference.

Mining real rubies is hard work done with a pickaxe, but mining ruby the language is simple With this book, you'll find it remarkably easy to Learn Ruby basics. You'll find normal stuff like classes, objects, and exceptions, as well as more interesting features, such as infinite-precision integers, iterators, mixins, and threads.

  • Write large, well-structured Ruby programs
  • Write CGI scripts and create dynamic Ruby pages for the Web
  • Create cross-platform GUI applications
  • Access Microsoft Windows native API calls and automate Windows applications
  • Extend Ruby using C code

Other gems you'll find in Programming Ruby include:

  • An alphabetical reference to all of the built-in classes, modules, and the standard library, documenting over a thousand methods
  • A reference to object-oriented design libraries, network and Web libraries, and Microsoft Windows support
  • A guide to downloading the Ruby language itself, as well as other Ruby resources
  • Numerous examples (that really work) appear throughout the book. You will come away from this book with an appreciation for Ruby's power, flexibility, and clarity. You'll be armed with the information you need to put Ruby to work for you and your projects.

The authors maintain the Ruby FAQ, which can be found on-line at both www.rubycentral.com and www.pragmaticprogrammer.com.



Sample Content

Table of Contents



Foreword.


Preface.


1. Roadmap.

I. FACETS OF RUBY.

2. Ruby New.

Ruby Is an Object-Oriented Language.

Some Basic Ruby.

Arrays and Hashes.

Control Structures.

Regular Expressions.

Blocks and Iterators.

Reading and ‘Riting.

Onward and Upward.

3. Classes, Objects, and Variables.

Inheritance and Messages.

Objects and Attributes.

Class Variables and Class Methods.

Access Control.

Variables.

4. Containers, Blocks, and Iterators.

Containers.

Blocks and Iterators.

5. Standard Types.

Numbers.

Strings.

Ranges.

Regular Expressions.

6. More about Methods.

Defining a Method.

Calling a Method.

7. Expressions.

Operator Expressions.

Miscellaneous Expressions.

Assignment.

Conditional Execution.

Case Expressions.

Loops.

Variable Scope and Loops.

8. Exceptions, Catch, and Throw.

The Exception Class.

Handling Exceptions.

Raising Exceptions.

Catch and Throw.

9. Modules.

Namespaces.

Mixins.

Iterators and the Enumerable Module.

Including Other Files.

10. Basic Input and Output.

What Is an IO Object?

Opening and Closing Files.

Reading and Writing Files.

Talking to Networks.

11. Threads and Processes.

Multithreading.

Controlling the Thread Scheduler.

Mutual Exclusion.

Running Multiple Processes.

12. When Trouble Strikes.

Ruby Debugger.

Interactive Ruby.

But It Doesn't Work!

But It's Too Slow!

II. RUBY IN ITS SETTING.

13. Ruby and Its World.

Command-Line Arguments.

Program Termination.

Environment Variables.

Where Ruby Finds Its Modules.

Build Environment.

14. Ruby and the Web.

Writing CGI Scripts.

Embedding Ruby in HTML.

Improving Performance.

15. Ruby Tk.

Simple Tk Application.

Widgets.

Binding Events.

Canvas.

Scrolling.

Translating from Perl/Tk Documentation.

16. Ruby and Microsoft Windows.

Ruby Ports.

Running Ruby Under Windows.

Win32API.

Windows Automation.

17. Extending Ruby.

Ruby Objects in C.

Writing Ruby in C.

Sharing Data Between Ruby and C.

Memory Allocation.

Creating an Extension.

Embedding a Ruby Interpreter.

Bridging Ruby to Other Languages.

Ruby C Language API.

III. RUBY CRYSTALLIZED.

18. The Ruby Language.

Source Layout.

The Basic Types.

Names.

Variables and Constants.

Predefined Variables.

Expressions.

Boolean Expressions.

If and Unless Expressions.

Case Expressions.

Loop Constructs.

Method Definition.

Invoking a Method.

Aliasing.

Class Definition.

Module Definitions.

Access Control.

Blocks, Closures, and Proc Objects.

Exceptions.

Catch and Throw.

19. Classes and Objects.

How Classes and Objects Interact.

Class and Module Definitions.

Top-Level Execution Environment.

Inheritance and Visibility.

Freezing Objects.

20. Locking Ruby in the Safe.

Safe Levels.

Tainted Objects.

21. Reflection, ObjectSpace, and Distributed Ruby.

Looking at Objects.

Looking at Classes.

Calling Methods Dynamically.

System Hooks.

Tracing Your Program's Execution.

Marshaling and Distributed Ruby.

Compile Time? Runtime? Anytime!

IV. RUBY LIBRARY REFERENCE.

22. Built-In Classes.

Alphabetical Listing.

Array.

Bignum.

Binding.

Class.

Continuation.

Dir.

Exception.

FalseClass.

File.

File::Stat.

Fixnum.

Float.

Hash.

Integer.

IO.

MatchData.

Method.

Module.

NilClass.

Numeric.

Object.

Proc.

Range.

Regexp.

String.

Struct.

Struct::Tms.

Symbol.

Thread.

ThreadGroup.

Time.

TrueClass.

23. Built-in Modules.

Alphabetical Listing.

Comparable.

Enumerable.

Errno.

FileTest.

GC.

Kernel.

Marshal.

Math.

ObjectSpace.

Process.

24. Standard Library.

Complex.

Date.

English.

Find.

File.

GetoptLong.

mkmf.

ParseDate.

profile.

PStore.

Tempfile.

Mutex.

ConditionVariable.

timeout.

WeakRef.

25. Object-Oriented Design Libraries.

Visitor.

Delegate.

Observer.

Singleton.

26. Network and Web Libraries.

Socket-Level Access.

BasicSocket.

IPSocket.

TCPSocket.

SOCKSSocket.

TCPServer.

UDPSocket.

UNIXSocket.

UNIXServer.

Socket.

Higher-Level Access.

Net::FTP.

Net::HTTP.

Net::HTTPResponse.

Net::POP.

Net::APOP.

Net::POPMail.

Net::SMTP.

Net::Telnet.

CGI Development.

CGI.

CGI::Session.

27. Microsoft Windows Support.

WIN32OLE.

WIN32OLE_EVENT.

Win32API.

V. APPENDICES.

A: Embedded Documentation.

Inline Formatting.

Cross References.

Method Names.

Including Other Files.

Using rdtool.

Mandatory Disclaimer.

B: Interactive Ruby Shell.

Command Line.

Initialization File.

Commands.

Restrictions.

rtags, xmp, and the Frame Class.

C: Support.

Web Sites.

Download Sites.

Usenet Newsgroup.

Mailing Lists.

Bug Reporting.

D: Bibliography.
Index. 0201710897T04062001

Preface

This book is a tutorial and reference for the Ruby programming language. Use Ruby, and you'll write better code, be more productive, and enjoy programming more.

These are bold claims, but we think that after reading this book you'll agree with them. And we have the experience to back up this belief.

As Pragmatic Programmers we've tried many, many languages in our search for tools to make our lives easier, for tools to help us do our jobs better. Until now, though, we'd always been frustrated by the languages we were using.

Our job is to solve problems, not spoonfeed compilers, so we like dynamic languages that adapt to us, without arbitrary, rigid rules. We need clarity so we can communicate using our code. We value conciseness and the ability to express a requirement in code accurately and efficiently. The less code we write, the less that can go wrong. (And our wrists and fingers are thankful, too.)

We want to be as productive as possible, so we want our code to run the first time; time spent in the debugger is time stolen from the development clock. It also helps if we can try out code as we edit it; if you have to wait for a 2-hour make cycle, you may as well be using punch cards and submitting your work for batch compilation.

We want a language that works at a high level of abstraction. The higher level the language, the less time we spend translating our requirements into code.

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.

Ruby Sparkles

Take a true object-oriented language, such as Smalltalk. Drop the unfamiliar syntax and move to more conventional, file-based source code. Now add in a good measure of the flexibility and convenience of languages such as Python and Perl.

You end up with Ruby.

OO aficionados will find much to like in Ruby: things such as pure object orientation (everything's an object), metaclasses, closures, iterators, and ubiquitous heterogeneous collections. Smalltalk users will feel right at home (and C++ and Java users will feel jealous).

At the same time, Perl and Python wizards will find many of their favorite features: full regular expression support, tight integration with the underlying operating system, convenient shortcuts, and dynamic evaluation.

Ruby is easy to learn. Everyday tasks are simple to code, and once you've done them, they are easy to maintain and grow. Apparently difficult things often turn out not to have been difficult after all. Ruby follows the Principle of Least Surprise---things work the way you would expect them to, with very few special cases or exceptions. And that really does make a difference when you're programming. We call Ruby a transparent language. By that we mean that Ruby doesn't obscure the solutions you write behind lots of syntax and the need to churn out reams of support code just to get simple things done. With Ruby you write programs close to the problem domain. Rather than constantly mapping your ideas and designs down to the pedestrian level of most languages, with Ruby you'll find you can express them directly and express them elegantly. This means you code faster. It also means your programs stay readable and maintainable.

Using Ruby, we are constantly amazed at how much code we can write in one sitting, code that works the first time. There are very few syntax errors, no type violations, and far fewer bugs than usual. This makes sense: there's less to get wrong. No bothersome semicolons to type mechanically at the end of each line. No troublesome type declarations to keep in sync (especially in separate files). No unnecessary words just to keep the compiler happy. No error-prone framework code.

So why learn Ruby? Because we think it will help you program better. It will help you to focus on the problem at hand, with fewer distractions. It will make your life easier.

What Kind of Language Is Ruby?

In the old days, the distinction between languages was simple: they were either compiled, like C or Fortran, or interpreted, like BASIC. Compiled languages gave you speed and low-level access; interpreted languages were higher-level but slower.

Times change, and things aren't that simple anymore. Some language designers have taken to calling their creations ''scripting languages.'' By this, we guess they mean that their languages are interpreted and can be used to replace batch files and shell scripts, orchestrating the behavior of other programs and the underlying operating system. Perl, TCL, and Python have all been called scripting languages. What exactly is a scripting language? Frankly we don't know if it's a distinction worth making. In Ruby, you can access all the underlying operating system features. You can do the same stuff in Ruby that you can in Perl or Python, and you can do it more cleanly. But Ruby is fundamentally different. It is a true programming language, too, with strong theoretical roots and an elegant, lightweight syntax. You could hack together a mess of ''scripts'' with Ruby, but you probably won't. Instead, you'll be more inclined to engineer a solution, to produce a program than is easy to understand, simple to maintain, and a piece of cake to extend and reuse in the future. Although we have used Ruby for scripting jobs, most of the time we use it as a general-purpose programming language. We've used it to write GUI applications and middle-tier server processes, and we're using it to format large parts of this book. Others have used it for managing server machines and databases. Ruby is serving Web pages, interfacing to databases and generating dynamic content. People are writing artificial intelligence and machine learning programs in Ruby, and at least one person is using it to investigate natural evolution. Ruby's finding a home as a vehicle for exploratory mathematics. And people all over the world are using it as a way of gluing together all their different applications. It truly is a great language for producing solutions in a wide variety of problem domains.

Is Ruby for Me?

Ruby is not the universal panacea for programmers' problems. There will always be times when you'll need a particular language: the environment may dictate it, you may have special libraries you need, performance concerns, or simply an issue with training. We haven't given up languages such as Java and C++ entirely (although there are times when we wish we could).

However, Ruby is probably more applicable than you might think. It is easy to extend, both from within the language and by linking in third-party libraries. It is portable across a number of platforms. It's relatively lightweight and consumes only modest system resources. And it's easy to learn; we've known people who've put Ruby code into production systems within a day of picking up drafts of this book. We've used Ruby to implement parts of an X11 window manager, a task that's normally considered severe C coding. Ruby excelled, and helped us write code in hours that would otherwise have taken days.

Once you get comfortable with Ruby, we think you'll keep coming back to it as your language of choice.

Why Did We Write This Book?

So we'd just finished writing The Pragmatic Programmer, our families had just started talking to us again, and suddenly we felt the need to write another book. Why? We guess it comes down to a kind of missionary zeal.

Ruby was created by Yukihiro Matsumoto (Matz) in Japan. Since 1995, its popularity in Japan has grown at an astounding rate; there are rumors that Ruby is more popular than Python in Japan. But to date, much of the detailed Ruby documentation is in Japanese. It probably isn't a programming language you'd just stumble across.

We wanted to spread the word, to have more people outside Japan using Ruby and enjoying the benefits, so we decided to document Ruby in English. And what started out as a small project just sort of grew....

Ruby Versions

This book documents Version 1.6 of Ruby, which was released in September 2000.

Ruby version numbering follows the same scheme used for many other open source projects. Releases with even subversion numbers (1.0, 1.2, 1.4, and so on) are stable, public releases. These are the releases that are prepackaged and made available on the various Ruby Web sites.

Development versions of the software have odd subversion numbers, such as 1.1 and 1.3. These you'll have to download and build for yourself.



0201710897P04062001

Updates

Errata

Click below for Errata related to this title:
Errata

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020