Home > Store

Eloquent Ruby

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

Eloquent Ruby

Best Value Purchase

Book + eBook Bundle

  • Your Price: $54.29
  • List Price: $86.98
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.

More Purchase Options


  • Your Price: $42.39
  • List Price: $52.99
  • Usually ships in 24 hours.

eBook (Watermarked)

  • Your Price: $27.19
  • List Price: $33.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.


  • Copyright 2011
  • Dimensions: 7" x 9-1/8"
  • Pages: 448
  • Edition: 1st
  • Book
  • ISBN-10: 0-321-58410-4
  • ISBN-13: 978-0-321-58410-6

It’s easy to write correct Ruby code, but to gain the fluency needed to write great Ruby code, you must go beyond syntax and absorb the “Ruby way” of thinking and problem solving. In Eloquent Ruby, Russ Olsen helps you write Ruby like true Rubyists do–so you can leverage its immense, surprising power.

Olsen draws on years of experience internalizing the Ruby culture and teaching Ruby to other programmers. He guides you to the “Ah Ha!” moments when it suddenly becomes clear why Ruby works the way it does, and how you can take advantage of this language’s elegance and expressiveness.

Eloquent Ruby

starts small, answering tactical questions focused on a single statement, method, test, or bug. You’ll learn how to write code that actually looks like Ruby (not Java or C#); why Ruby has so many control structures; how to use strings, expressions, and symbols; and what dynamic typing is really good for.

Next, the book addresses bigger questions related to building methods and classes. You’ll discover why Ruby classes contain so many tiny methods, when to use operator overloading, and when to avoid it. Olsen explains how to write Ruby code that writes its own code–and why you’ll want to. He concludes with powerful project-level features and techniques ranging from gems to Domain Specific Languages.

A part of the renowned Addison-Wesley Professional Ruby Series, Eloquent Ruby will help you “put on your Ruby-colored glasses” and get results that make you a true believer.

Sample Content

Online Sample Chapters

Eloquent Ruby: Embrace Dynamic Typing

Eloquent Ruby: Use Symbols to Stand for Something

Sample Pages

Download the sample pages (includes Chapters 6 & 8 and Index)

Table of Contents

Foreword xix

Preface xxi

Acknowledgments xxv

About the Author xxvii

PART I: The Basics 1

Chapter 1: Write Code That Looks Like Ruby 3

The Very Basic Basics 4

Go Easy on the Comments 6

Camels for Classes, Snakes Everywhere Else 8

Parentheses Are Optional but Are Occasionally Forbidden 9

Folding Up Those Lines 10

Folding Up Those Code Blocks 11

Staying Out of Trouble 12

In the Wild 13

Wrapping Up 15

Chapter 2: Choose the Right Control Structure 17

If, Unless, While, and Until 17

Use the Modifier Forms Where Appropriate 19

Use each, Not for 20

A Case of Programming Logic 21

Staying Out of Trouble 23

In the Wild 25

Wrapping Up 27

Chapter 3: Take Advantage of Ruby’s Smart Collections 29

Literal Shortcuts 29

Instant Arrays and Hashes from Method Calls 30

Running Through Your Collection 33

Beware the Bang! 36

Rely on the Order of Your Hashes 38

In the Wild 38

Staying Out of Trouble 40

Wrapping Up 42

Chapter 4: Take Advantage of Ruby’s Smart Strings 43

Coming Up with a String 44

Another API to Master 47

The String: A Place for Your Lines, Characters, and Bytes 49

In the Wild 50

Staying Out of Trouble 51

Wrapping Up 52

Chapter 5: Find the Right String with Regular Expressions 53

Matching One Character at a Time 54

Sets, Ranges, and Alternatives 55

The Regular Expression Star 57

Regular Expressions in Ruby 58

Beginnings and Endings 60

In the Wild 62

Staying Out of Trouble 63

Wrapping Up 64

Chapter 6: Use Symbols to Stand for Something 65

The Two Faces of Strings 65

Not Quite a String 66

Optimized to Stand for Something 67

In the Wild 69

Staying Out of Trouble 70

Wrapping Up 71

Chapter 7: Treat Everything Like an Object–Because Everything Is 73

A Quick Review of Classes, Instances, and Methods 74

Objects All the Way Down 76

The Importance of Being an Object 77

Public, Private, and Protected 79

In the Wild 81

Staying Out of Trouble 82

Wrapping Up 84

Chapter 8: Embrace Dynamic Typing 85

Shorter Programs, But Not the Way You Think 85

Extreme Decoupling 89

Required Ceremony Versus Programmer-Driven Clarity 92

Staying Out of Trouble 93

In the Wild 94

Wrapping Up 96

Chapter 9: Write Specs! 97

Test::Unit: When Your Documents Just Have to Work 98

A Plethora of Assertions 101

Don’t Test It, Spec It! 101

A Tidy Spec Is a Readable Spec 104

Easy Stubs 105

. . . And Easy Mocks 107

In the Wild 108

Staying Out of Trouble 110

Wrapping Up 113

PART II: Classes, Modules, and Blocks 115

Chapter 10: Construct Your Classes from Short, Focused Methods 117

Compressing Specifications 117

Composing Methods for Humans 121

Composing Ruby Methods 122

One Way Out? 123

Staying Out of Trouble 126

In the Wild 127

Wrapping Up 128

Chapter 11: Define Operators Respectfully 129

Defining Operators in Ruby 129

A Sampling of Operators 131

Operating Across Classes 134

Staying Out of Trouble 135

In the Wild 137

Wrapping Up 139

Chapter 12: Create Classes That Understand Equality 141

An Identifier for Your Documents 141

An Embarrassment of Equality 142

Double Equals for Everyday Use 143

Broadening the Appeal of the == Method 145

Well-Behaved Equality 146

Triple Equals for Case Statements 149

Hash Tables and the eql? Method 150

Building a Well-Behaved Hash Key 152

Staying Out of Trouble 153

In the Wild 154

Wrapping Up 156

Chapter 13: Get the Behavior You Need with Singleton and Class Methods 157

A Stubby Puzzle 158

A Hidden, but Real Class 160

Class Methods: Singletons in Plain Sight 162

In the Wild 164

Staying Out of Trouble 165

Wrapping Up 167

Chapter 14: Use Class Instance Variables 169

A Quick Review of Class Variables 169

Wandering Variables 171

Getting Control of the Data in Your Class 174

Class Instance Variables and Subclasses 175

Adding Some Convenience to Your Class Instance Variables 176

In the Wild 177

Staying Out of Trouble 179

Wrapping Up 179

Chapter 15: Use Modules as Name Spaces 181

A Place for Your Stuff, with a Name 181

A Home for Those Utility Methods 184

Building Modules a Little at a Time 185

Treat Modules Like the Objects That They Are 186

Staying Out of Trouble 189

In the Wild 190

Wrapping Up 191

Chapter 16: Use Modules as Mixins 193

Better Books with Modules 193

Mixin Modules to the Rescue 195

Extending a Module 197

Staying Out of Trouble 198

In the Wild 202

Wrapping Up 205

Chapter 17: Use Blocks to Iterate 207

A Quick Review of Code Blocks 207

One Word after Another 209

As Many Iterators as You Like 210

Iterating over the Ethereal 211

Enumerable: Your Iterator on Steroids 213

Staying Out of Trouble 215

In the Wild 217

Wrapping Up 218

Chapter 18: Execute Around with a Block 219

Add a Little Logging 219

When It Absolutely Must Happen 224

Setting Up Objects with an Initialization Block 225

Dragging Your Scope along with the Block 225

Carrying the Answers Back 227

Staying Out of Trouble 228

In the Wild 229

Wrapping Up 231

Chapter 19: Save Blocks to Execute Later 233

Explicit Blocks 233

The Call Back Problem 234

Banking Blocks 236

Saving Code Blocks for Lazy Initialization 237

Instant Block Objects 239

Staying Out of Trouble 240

In the Wild 243

Wrapping Up 244

PART III: Metaprogramming 247

Chapter 20: Use Hooks to Keep Your Program Informed 249

Waking Up to a New Subclass 250

Modules Want To Be Heard Too 253

Knowing When Your Time Is Up 255

. . . And a Cast of Thousands 256

Staying Out of Trouble 257

In the Wild 259

Wrapping Up 261

Chapter 21: Use method_missing for Flexible Error Handling 263

Meeting Those Missing Methods 264

Handling Document Errors 266

Coping with Constants 267

In the Wild 268

Staying Out of Trouble 270

Wrapping Up 271

Chapter 22: Use method_missing for Delegation 273

The Promise and Pain of Delegation 274

The Trouble with Old-Fashioned Delegation 275

The method_missing Method to the Rescue 277

More Discriminating Delegation 278

Staying Out of Trouble 279

In the Wild 281

Wrapping Up 283

Chapter 23: Use method_missing to Build Flexible APIs 285

Building Form Letters One Word at a Time 286

Magic Methods from method_missing 287

It’s the Users That Count–All of Them 289

Staying Out of Trouble 289

In the Wild 290

Wrapping Up 292

Chapter 24: Update Existing Classes with Monkey Patching 293

Wide-Open Classes 294

Fixing a Broken Class 295

Improving Existing Classes 296

Renaming Methods with alias_method 297

Do Anything to Any Class, Anytime 299

In the Wild 299

Staying Out of Trouble 303

Wrapping Up 303

Chapter 25: Create Self-Modifying Classes 305

Open Classes, Again 305

Put Programming Logic in Your Classes 308

Class Methods That Change Their Class 309

In the Wild 310

Staying Out of Trouble 314

Wrapping Up 315

Chapter 26: Create Classes That Modify Their Subclasses 317

A Document of Paragraphs 317

Subclassing Is (Sometimes) Hard to Do 319

Class Methods That Build Instance Methods 321

Better Method Creation with define_method 324

The Modification Sky Is the Limit 324

In the Wild 327

Staying Out of Trouble 330

Wrapping Up 332

PART IV: Pulling It All Together 333

Chapter 27: Invent Internal DSLs 335

Little Languages for Big Problems 335

Dealing with XML 336

Stepping Over the DSL Line 341

Pulling Out All the Stops 344

In the Wild 345

Staying Out of Trouble 347

Wrapping Up 349

Chapter 28: Build External DSLs for Flexible Syntax 351

The Trouble with the Ripper 352

Internal Is Not the Only DSL 353

Regular Expressions for Heavier Parsing 356

Treetop for Really Big Jobs 358

Staying Out of Trouble 360

In the Wild 362

Wrapping Up 364

Chapter 29: Package Your Programs as Gems 367

Consuming Gems 367

Gem Versions 368

The Nuts and Bolts of Gems 369

Building a Gem 370

Uploading Your Gem to a Repository 374

Automating Gem Creation 375

In the Wild 376

Staying Out of Trouble 377

Wrapping Up 380

Chapter 30: Know Your Ruby Implementation 381

A Fistful of Rubies 381

MRI: An Enlightening Experience for the C Programmer 382

YARV: MRI with a Byte Code Turbocharger 385

JRuby: Bending the “J” in the JVM 387

Rubinius 388

In the Wild 389

Staying Out of Trouble 389

Wrapping Up 390

Chapter 31: Keep an Open Mind to Go with Those Open Classes 391

Appendix: Going Further 393

Index 397


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.


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.


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.


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.


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


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


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.


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.


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