Thanks to the popularity of the Ruby on Rails Web application framework, Ruby is rapidly becoming one of the major programming languages of the twenty-first century, and learning Ruby no
Trang 1this print for content only—size & color not accurate spine = 1.25" 664 page count
Beginning Ruby
Dear Reader,
Beginning Ruby is the only book you’ll need to take yourself from the point of
not knowing Ruby at all to the point of being proficient in the language You’ll
be able to develop your own complete applications that can work online, access databases, process files, and more.
Thanks to the popularity of the Ruby on Rails Web application framework, Ruby is rapidly becoming one of the major programming languages of the twenty-first century, and learning Ruby now will give you an enviable advan- tage over other developers I’ve written this book in a way that lets you learn easily how to develop modern software and Internet-driven applications using Ruby’s terminology, techniques, and culture You’ll then be able to discover fur- ther resources and tutorials online for the more advanced topics you’ll want to learn once you become a Ruby professional
My own Ruby learning experience is my motivation for writing this book I wanted to write a book that wouldn’t assume you’re already an object-orientation
or dynamic programming expert, and that would cover Ruby’s more oblique areas in a style suitable for beginners and intermediate developers alike I wrote
Beginning Ruby so that someone with no programming experience, through to
someone who is reasonably proficient in another programming language, can quickly learn and appreciate the details of Ruby and the culture surrounding it.
Most of the topics necessary to become a professional Ruby developer are explained in detail, and the chapters are structured in such a way that more advanced developers can quickly skip sections not relevant to them.
From the start my ambition has been to design a book to educate and encourage, rather than to deliver dry facts This book not only shows you how
to program with Ruby, it also teaches you how the Ruby community works, where the best places are to find help, and how to “walk the walk” and “talk the talk.”
9 781590 597668
5 3 9 9 9
Companion eBook Available
An instructional guide to the Ruby programming language.
Rails Solutions:
Ruby on Rails Made Easy
Pro Ruby on Rails
Practical Ruby Gems Beginning Ruby
Beginning Ruby on Rails
Trang 2Peter Cooper
Beginning Ruby
From Novice to Professional
Trang 3Beginning Ruby: From Novice to Professional
Copyright © 2007 by Peter Cooper
All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-59059-766-8
ISBN-10 (pbk): 1-59059-766-4
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
Lead Editors: Jonathan Gennick, Keir Thomas
Technical Reviewers: Tim Fletcher, Peter Marklund
Editorial Board: Steve Anglin, Ewan Buckingham, Gary Cornell, Jason Gilmore, Jonathan Gennick, Jonathan Hassell, James Huddleston, Chris Mills, Matthew Moodie, Jeff Pepper, Paul Sarknas, Dominic Shakeshaft, Jim Sumser, Matt Wade
Project Manager: Beth Christmas
Copy Edit Manager: Nicole Flores
Copy Editor: Susannah Davidson Pfalzer
Assistant Production Director: Kari Brooks-Copony
Production Editor: Lori Bring
Compositor: Gina Rexrode
Proofreader: Nancy Sixsmith
Indexer: Julie Grady
Artist: April Milne
Cover Designer: Kurt Krames
Manufacturing Director: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or visit http://www.springeronline.com
For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219,
Berkeley, CA 94710 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit
http://www.apress.com
The information in this book is distributed on an “as is” basis, without warranty Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work
The source code for this book is available to readers at http://www.apress.com in the Source Code/ Download section
Trang 4For Laura
Trang 6Contents at a Glance
Foreword xix
About the Author xxiii
About the Technical Reviewers xxv
Acknowledgments xxvii
Introduction xxix
PART 1 ■ ■ ■ Foundations and Scaffolding ■CHAPTER 1 Let’s Get It Started: Installing Ruby 3
■CHAPTER 2 Programming == Joy: A Whistle-Stop Tour of Ruby and Object Orientation 15
■CHAPTER 3 Ruby’s Building Blocks: Data, Expressions, and Flow Control 35
■CHAPTER 4 Developing a Basic Ruby Application 87
■CHAPTER 5 The Ruby Ecosystem 113
PART 2 ■ ■ ■ The Core of Ruby ■CHAPTER 6 Classes, Objects, and Modules 129
■CHAPTER 7 Projects and Libraries 181
■CHAPTER 8 Documentation, Error Handling, Debugging, and Testing 201
■CHAPTER 9 Files and Databases 229
■CHAPTER 10 Deploying Ruby Applications and Libraries 279
■CHAPTER 11 Advanced Ruby Features 309
■CHAPTER 12 Tying It Together: Developing a Larger Ruby Application 341
PART 3 ■ ■ ■ Ruby Online ■CHAPTER 13 Ruby on Rails: Ruby’s Killer App 387
■CHAPTER 14 Ruby and the Internet 433
■CHAPTER 15 Networking, Sockets, and Daemons 467
■CHAPTER 16 Useful Ruby Libraries and Gems 493
v
Trang 7■APPENDIX A Ruby Primer and Review for Developers 549
■APPENDIX B Ruby Reference 581
■APPENDIX C Useful Resources 601
■INDEX 611
Trang 8Foreword xix
About the Author xxiii
About the Technical Reviewers xxv
Acknowledgments xxvii
Introduction xxix
PART 1 ■ ■ ■ Foundations and Scaffolding ■CHAPTER 1 Let’s Get It Started: Installing Ruby 3
Installing Ruby 4
Windows 4
Apple Mac OS X 7
Linux 10
Other Platforms 12
Summary 13
■CHAPTER 2 Programming == Joy: A Whistle-Stop Tour of Ruby and Object Orientation 15
Baby Steps 16
irb: Interactive Ruby 16
Ruby Is English for Computers 17
Why Ruby Makes a Great Programming Language 17
Trails for the Mind 18
Turning Ideas into Ruby Code 20
How Ruby Understands Concepts with Objects and Classes 20
The Making of a Man 21
Basic Variables 23
From People to Pets 24
Everything Is an Object 27
Kernel Methods 29
Passing Data to Methods 29
Using the Methods of the String Class 31
Using Ruby Without Object Orientation 32
Summary 33
vii
Trang 9■CHAPTER 3 Ruby’s Building Blocks: Data, Expressions, and
Flow Control 35
Numbers and Expressions 35
Basic Expressions 35
Variables 36
Comparison Operators and Expressions 38
Looping Through Numbers with Blocks and Iterators 40
Floating Point Numbers 42
Constants 43
Text and Strings 44
String Literals 44
String Expressions 46
Interpolation 47
String Methods 49
Regular Expressions and String Manipulation 50
Arrays and Lists 57
Basic Arrays 58
Splitting Strings into Arrays 60
Array Iteration 61
Other Array Methods 62
Hashes 65
Basic Hash Methods 66
Hashes Within Hashes 67
Flow Control 68
if and unless 69
?:, The Ternary Operator 70
elsif and case 71
while and until 72
Code Blocks 74
Other Useful Building Blocks 76
Dates and Times 76
Large Numbers 80
Ranges 81
Symbols 83
Converting Between Classes 84
Summary 85
■CHAPTER 4 Developing a Basic Ruby Application 87
Working with Source Code Files 87
Creating a Test File 88
The Test Source Code File 90
Running Your Source Code 90
Trang 10Our Application: A Text Analyzer 93
Required Basic Features 94
Building the Basic Application 94
Obtaining Some Dummy Text 95
Loading Text Files and Counting Lines 95
Counting Characters 97
Counting Words 98
Counting Sentences and Paragraphs 100
Calculating Averages 102
The Source Code So Far 102
Adding Extra Features 103
Percentage of “Useful” Words 103
Summarizing by Finding “Interesting” Sentences 105
Analyzing Files Other Than text.txt 107
The Completed Program 108
Summary 111
■CHAPTER 5 The Ruby Ecosystem 113
Ruby’s History 113
The Land of the Rising Sun 114
Ruby’s Influences 115
Go West 115
Ruby on Rails 117
Why Rails Came into Existence 118
How the Web (2.0) Was Won 119
The Open Source Culture 119
What Is Open Source? 120
Where and How to Get Help 121
Mailing Lists 121
Usenet Newsgroups 121
Internet Relay Chat (IRC) 122
Documentation 123
Forums 124
Joining the Community 124
Give Help to Others 124
Contribute Code 125
Weblogs 125
Summary 126
Trang 11PART 2 ■ ■ ■ The Core of Ruby
■CHAPTER 6 Classes, Objects, and Modules 129
Why Use Object Orientation? 129
Object Orientation Basics 133
Local, Global, Object, and Class Variables 133
Class Methods vs Object Methods 138
Inheritance 140
Overriding Existing Methods 143
Reflection and Discovering an Object’s Methods 145
Encapsulation 146
Polymorphism 151
Nested Classes 153
The Scope of Constants 154
Modules, Namespaces, and Mix-Ins 156
Namespaces 156
Mix-Ins 159
Building a Dungeon Text Adventure with Objects 168
Dungeon Concepts 168
Creating the Initial Classes 168
Structs: Quick and Easy Data Classes 170
Creating Rooms 173
Making the Dungeon Work 173
Summary 178
■CHAPTER 7 Projects and Libraries 181
Projects and Using Code from Other Files 181
Basic File Inclusion 181
Inclusions from Other Directories 184
Logic and Including Code 185
Nested Inclusions 185
Libraries 186
The Standard Libraries 187
RubyGems 189
Summary 198
■CHAPTER 8 Documentation, Error Handling, Debugging, and Testing 201
Documentation 201
Generating Documentation with RDoc 202
RDoc Techniques 203
Trang 12Debugging and Errors 208
Exceptions and Error Handling 208
Catch and Throw 212
The Ruby Debugger 213
Testing 216
The Philosophy of Test-Driven Development 217
Unit Testing 219
More Test::Unit Assertions 221
Benchmarking and Profiling 222
Simple Benchmarking 223
Profiling 225
Summary 227
■CHAPTER 9 Files and Databases 229
Input and Output 229
Keyboard Input 230
File I/O 231
Basic Databases 248
Text File Databases 248
Storing Objects and Data Structures 251
Relational Databases and SQL 255
Relational Database Concepts 256
The Big Four: MySQL, PostgreSQL, Oracle, and SQLite 257
Installing SQLite 258
A Crash Course in Basic Database Actions and SQL 259
Using SQLite with Ruby 264
Connecting to Other Database Systems 269
ActiveRecord: A Sneak Peek 274
Summary 275
■CHAPTER 10 Deploying Ruby Applications and Libraries 279
Distributing Basic Ruby Programs 279
The Shebang Line 280
Associated File Types in Windows 282
“Compiling” Ruby 282
Detecting Ruby’s Runtime Environment 284
Easy OS Detection with RUBY_PLATFORM 285
Environment Variables 285
Accessing Command Line Arguments 287
Trang 13Distributing and Releasing Ruby Libraries As Gems 288
Creating a Gem 289
Distributing a Gem 293
RubyForge 294
Deploying Ruby Applications As Remote Services 295
CGI Scripts 295
Generic HTTP Servers 298
Remote Procedure Calls 303
Summary 308
■CHAPTER 11 Advanced Ruby Features 309
Dynamic Code Execution 309
Bindings 310
Other Forms of eval 311
Creating Your Own Version of attr_accessor 314
Running Other Programs from Ruby 315
Getting Results from Other Programs 315
Transferring Execution to Another Program 316
Running Two Programs at the Same Time 316
Interacting with Another Program 317
Safely Handling Data and Dangerous Methods 318
Tainted Data and Objects 319
Safe Levels 321
Working with Microsoft Windows 322
Using the Windows API 323
Controlling Windows Programs 325
Threads 327
Basic Ruby Threads in Action 328
Advanced Thread Operations 329
RubyInline 331
Why Use C As an Inline Language? 332
Creating a Basic Method or Function 332
Benchmarking C vs Ruby 334
Unicode and UTF-8 Support 336
Summary 339
■CHAPTER 12 Tying It Together: Developing a Larger Ruby Application 341
Let’s Build a Bot 341
What Is a Bot? 341
Why a Bot? 343
How? 343
Trang 14Creating a Text Processing Tools Library 344
Building the WordPlay Library 345
Testing the Library 351
WordPlay’s Source Code 354
Building the Bot’s Core 357
The Program’s Life Cycle and Parts 358
Bot Data 360
Constructing the Bot Class and Data Loader 363
The response_to Method 365
Playing with the Bot 371
Main Bot Code Listings 374
bot.rb 375
basic_client.rb 378
Extending the Bot 378
Using Text Files As a Source of Conversation 379
Connecting the Bot to the Web 379
Bot-to-Bot Conversations 382
Summary 384
PART 3 ■ ■ ■ Ruby Online ■CHAPTER 13 Ruby on Rails: Ruby’s Killer App 387
First Steps 387
What Is Rails and Why Use It? 387
Installing Rails 389
Database Considerations 391
Building a Basic Rails Application 391
Creating a Blank Rails Application 391
Database Initialization 396
Creating a Model and Migrations 398
Scaffolding 404
Controllers and Views 408
Routing 418
Model Relationships 420
Sessions and Filters 422
Other Features 424
Layouts 424
Testing 426
Plugins 428
References and Demo Applications 429
Reference Sites and Tutorials 429
Example Rails Applications 430
Summary 430
Trang 15■CHAPTER 14 Ruby and the Internet 433
HTTP and the Web 433
Downloading Web Pages 433
Generating Web Pages and HTML 443
Processing Web Content 448
E-Mail 454
Receiving Mail with POP3 454
Sending Mail with SMTP 456
Sending Mail with ActionMailer 457
File Transfers with FTP 458
Connection and Basic FTP Actions 459
Downloading Files 461
Uploading Files 462
Summary 464
■CHAPTER 15 Networking, Sockets, and Daemons 467
Networking Concepts 467
TCP and UDP 468
IP Addresses and DNS 468
Basic Network Operations 469
Checking Machine and Service Availability 469
Performing DNS Queries 471
Connecting to a TCP Server Directly 474
Servers and Clients 475
UDP Client and Server 475
Building a Simple TCP Server 478
Multi-Client TCP Servers 480
GServer 482
A GServer-Based Chat Server 485
Web/HTTP Servers 488
Daemon Processes 488
Summary 490
■CHAPTER 16 Useful Ruby Libraries and Gems 493
abbrev 494
Installation 494
Examples 494
Further Information 495
base64 496
Installation 496
Examples 496
Further Information 499
Trang 16BlueCloth 500
Installation 500
Examples 500
Further Information 501
cgi 502
Installation 502
Examples 502
Further Information 507
chronic 508
Installation 508
Examples 508
Further Information 509
Digest 510
Installation 510
Examples 510
Further Information 512
English 513
Installation 513
Examples 513
Further Information 514
ERB 515
Installation 515
Examples 515
Further Information 518
FasterCSV 519
Installation 519
Examples 519
Further Information 525
iconv 526
Installation 526
Examples 526
Further Information 527
logger 528
Installation 528
Examples 528
Further Information 530
pp 531
Installation 531
Examples 531
Further Information 532
RedCloth 533
Installation 533
Examples 533
Further Information 534
Trang 17StringScanner 535
Installation 535
Examples 535
Further Information 538
tempfile 539
Installation 539
Examples 539
Further Information 541
uri 542
Installation 542
Examples 542
Further Information 546
zlib 547
Installation 547
Examples 547
Further Information 548
■APPENDIX A Ruby Primer and Review for Developers 549
The Basics 549
Definition and Concepts 549
The Ruby Interpreter and Running Ruby Code 551
Interactive Ruby 553
Expressions, Logic, and Flow Control 553
Basic Expressions 553
Class Mismatches 554
Comparison Expressions 555
Flow 557
Object Orientation 561
Objects 562
Classes and Methods 563
Reflection 565
Reopening Classes 567
Method Visibility 568
Data 569
Strings 569
Regular Expressions 569
Numbers 572
Arrays 574
Hashes (Associative Arrays) 574
Complex Structures 576
Input/Output 576
Files 577
Databases 577
Web Access 578
Trang 18Libraries 579
File Organization 579
Packaging 580
■APPENDIX B Ruby Reference 581
Useful Classes and Methods 581
Array 581
Bignum and Fixnum 583
Enumerable 584
Float 585
Hash 585
Integer 586
Numeric 586
Object 587
String 588
Regular Expression Syntax 590
Regular Expression Options 591
Special Characters and Formations 591
Character and Sub-Expression Suffixes 592
Exception Classes 592
Special Variables 596
Ruby License 597
■APPENDIX C Useful Resources 601
References 601
Ruby 601
Ruby on Rails 602
Blogs 603
Aggregators and Community Blogs 603
Personal Blogs 604
Forums and Newsgroups 604
Mailing Lists 605
Real-Time Chat 606
Tutorials and Guides 607
Installation 607
Ruby and Techniques 608
Ruby on Rails 609
Other 610
■INDEX 611
Trang 20xix
Trang 22why the lucky stiff
http://whytheluckystiff.net/
Trang 24About the Author
■PETER COOPERis an experienced Ruby developer and trainer, and tor of Ruby Inside (http://www.rubyinside.com/), the most popularRuby news blog Until 2007 he was primarily a Ruby trainer anddeveloper, but is now the full-time owner and developer of FeedDigest (http://www.feeddigest.com/), a Ruby- and Rails-powered RSSfeed processing and redistribution service that serves more than 200
edi-million requests per month and was recently profiled by Business 2.0 magazine.
Since 2004 Peter has developed many commercial Web sites using Ruby on Rails, theRuby-based Web framework In addition, he created Code Snippets (http://www.bigbold
com/snippets/), one of the Web’s largest public code repositories, and Congress, an online
chat client using Ajax and Ruby on Rails technologies
In addition to development work, Peter has written professionally about variousdevelopment techniques and tools, with more than 100 bylines since 1998 He was co-
editor of WebDeveloper.com, and worked on iBoost.com and Webpedia.com during the
dot-com boom
He lives in Lincolnshire, England, with his girlfriend In his limited spare time heenjoys hiking, camping, and exploring
xxiii
Trang 26About the
Technical Reviewers
■TIM FLETCHERis 22 years old and lives in Winchester, England, on a student placement
with IBM He likes Ruby because it’s fun He has no children or pets, but an admirable
younger sister called Sophie When not writing code, he loves to read, eat, sleep, and ski
as much as possible
■PETER MARKLUNDhas extensive experience with and expertise inobject orientation, Web development, relational databases, and test-ing, and has been doing Web development with Java and Tcl since
2000 He was one of the core developers of the OpenACS opensource Web framework In late 2004, he was introduced to Ruby onRails and has since helped develop an online community and a CRMsystem with Rails Peter is working as a Ruby on Rails freelancer and is also helping
organize events for the Ruby on Rails developer community in Stockholm Peter has a
personal blog at http://marklunds.com, where he shares Rails tips with other developers
xxv
Trang 28It is often said that writing is a lonely task, but it’s not until you write a book that you
realize the process has to be anything but lonely Without the help and reassurance of the
large team of people backing this book, and backing me personally, this book could not
have been written
My first thanks go to Keir Thomas, who approached me with the idea of writing aRuby book He gave me great freedom over the scope and specification of the book and
was the most essential piece of the puzzle in getting the book approved and everything
sorted out in the early stages
Beth Christmas of Apress deserves a special thanks for her superb project ment and constant reassurance during the writing of this book Without her schedules
manage-and assurance that everything was on track, I would have been a nervous wreck
Jonathan Gennick, Tim Fletcher, and Peter Marklund deserve much praise for theirseemingly unending reading and rereading of this book’s chapters throughout the vari-
ous stages of their development As a newcomer to Ruby, Jonathan provided some
especially interesting insights that have served to make the book even better for Ruby
newcomers to read
I’d also like to praise Susannah Davidson Pfalzer for her diligent approach to copyediting this book by fixing my pronouns, removing my overuse of words like “however”
and “therefore,” and generally making it possible to read the book without going insane
As this is my first book for Apress, I have depended on Susannah’s deep knowledge of
Apress customs a great deal
Naturally, thanks go to all of those I directly worked with on the book, whetherthey’re from Apress or independent In no particular order: Jonathan Gennick, Keir
Thomas, Beth Christmas, Tim Fletcher, Peter Marklund, Susannah Davidson Pfalzer,
Jason Gilmore, Lori Bring, Nancy Sixsmith, and why the lucky stiff
Separately from the book itself, I have to give thanks to many in the Ruby communityfor either working alongside me, producing tools I’ve used, or just making the Ruby lan-
guage more appealing in general In no particular order: why the lucky stiff (for an
unforgettable foreword), Yukihiro “Matz” Matsumoto, Jamie van Dyke, Amy Hoy, Evan
Weaver, Geoffrey Grosenbach, Obie Fernandez, Damien Tanner, Chris Roos, Martin
Sadler, Zach Dennis, Pat Toner, Pat Eyler, Hendy Irawan, Ian Ozsvald, Nic Williams, Shane
Vitarana, Josh Catone, Alan Bradburne, Jonathan Conway, Alex MacCaw, Benjamin
Cur-tis, and David Heinemeier Hansson I am anxious I’ve missed some names, so if you’re
missing from this list, I humbly apologize
Those in my personal life have also supported me a great deal by putting up with myweird work hours and annoying habits, and by asking questions about the book, feeding
xxvii
Trang 29me, or just being there to talk to In this regard I’d like to thank—again in no particularorder—Laura Craggs, Clive Cooper, Ann Cooper, David Sculley, Ed Farrow, Michael Wong,Bob Pardoe, Dave Hunt, Chris Ueland, Kelly Smith, Graham Craggs, Lorraine Craggs, andRobert Smith Laura Craggs deserves a special mention for having had to put up with menearly 24 hours a day during the writing of this book; she is amazing.
Last, it’s necessary to thank you, the reader, for choosing to buy this book, for if no
one bought this book, these acknowledgments and the efforts of many people during the writing of this book would have been wasted Thank you!
Trang 30I wanted to minimize my frustration during programming, so I want to minimize
my effort in programming That was my primary goal in designing Ruby I want to have fun in programming myself.
—Yukihiro Matsumoto (Matz), creator of Ruby
Ruby is a “best of breed” language that has been assembled from the best and most powerful programming features found in its predecessors.
—Jim White
Ruby makes me smile.
—Amy Hoy (slash7.com)
Ruby is a fun toy It’s also a serious programming language Ruby is the jolly uncle who
keeps the kids entertained, but who puts in solid 12-hour days at the construction site
during the week To hundreds of thousands of programmers, Ruby has become a good
friend, a trusted servant, and has revealed a new way of thinking about programming
and software development
Like the guitar, it’s often claimed that Ruby is an easy language to learn and a hardone to master I’d agree, with some provisions If you don’t know any programming
languages already, Ruby will be surprisingly easy to learn If you already know some
lan-guages such as PHP, Perl, BASIC, C, or Pascal, some of the concepts in Ruby will already
be familiar to you, but the different perspective Ruby takes with problem solving will
probably throw you at first Like the differences between spoken languages, Ruby differs
from most other programming languages not only by syntax, but by culture, grammar,
and customs In fact, Ruby has more in common with more esoteric languages such as
LISP and Smalltalk than with better-known languages such as PHP and C++
While Ruby’s roots might be different from other languages, it’s heavily used andrespected in many industries Companies that use or support Ruby in one way or another
include such prestigious names as Sun Microsystems, Intel, Microsoft, Apple, and
Amazon.com The Ruby on Rails Web framework is a system for developing Web
applica-tions that uses Ruby as its base language, and it powers hundreds of large Web sites
Ruby is also used as a generic language from the command prompt, much like Perl xxix
Trang 31Grammarians, biochemists, database administrators, and thousands of other sionals and hobbyists use Ruby to make their work easier Ruby is a truly internationallanguage with almost unlimited application.
profes-This book is designed to cater both to people new to programming and those withprogramming experience in other languages Ruby’s culture is different enough fromother languages that most of this book will be of use to both groups Any large sectionsthat can be skipped by already proficient programmers are noted in the text In any case,I’d suggest that all programmers at least speed-read the sections that might seem obvious
to them, as there are some surprising ways in which Ruby is different from what you’vedone before
When reading this book be prepared for a little informality, some quirky examples,and a heavy dose of pragmatism Ruby is an extremely pragmatic language, less con-cerned with formalities and more concerned with ease of development and valid results.From time to time I’ll show you how you can do things the “wrong” way in Ruby, merelyfor illustrative purposes, but mostly you’ll be working with code that does things “theRuby way.” When I started to learn Ruby I learned primarily by example, and with a lan-guage as original and idiomatic as Ruby, it’s the easiest way to pick up good habits for thefuture However, there’s always “more than one way to do it,” so if you think some code inthis book could be rewritten in a different way that fits in more with your way of thinking,try it out!
As you start this book, be prepared to think in new ways, and to feel motivated tostart coding for both fun and profit Ruby has helped a lot of jaded developers becomeproductive once again, and whether you’re a beginner to programming or one of thosejaded programmers, it’s almost inevitable that you’ll see how Ruby can be both fun andproductive for you
Last, if you’re coming from other modern scripting languages such as Perl, PHP, orPython, you might want to jump to Appendix A before reading Chapter 1 It covers thekey differences between Ruby and other scripting languages, which might help you movethrough the initial chapters of this book more easily
Good luck, and I hope you enjoy this book I’ll see you in Chapter 1
Trang 32Foundations and
Scaffolding
T his section is where the foundations of your Ruby knowledge will be laid By the end of this section you’ll be able to develop a complete, though basic, Ruby program You’ll learn how to get Ruby working, what object orientation is, how to develop some basic programs, and about the data types and control structures Ruby uses and can operate on Finally, I’ll walk you through creating a small program from start to finish.
P A R T 1
Trang 34Let’s Get It Started: Installing
Ruby
Ruby is a popular programming language, but not many computers understand it by
default This chapter takes you through the steps necessary to get Ruby working on your
computer
As an open source language, Ruby has been converted (or “ported,” as is the cal term) to run on many different computer platforms and architectures This means
techni-that if you develop a Ruby program on one machine, it’s likely you’ll be able to run it
without any changes on a different machine You can use Ruby, in one form or another,
on all the following operating systems and platforms:
• Microsoft Windows 95, 98, XP, and Vista (all varieties)
• Mac OS X (all varieties)
• Linux (all varieties)
• Symbian Series 60 cell phones
• Any platform for which a Java Virtual Machine exists (using JRuby, rather than theofficial Ruby interpreter)
3
C H A P T E R 1
Trang 35■ Caution Some specifics of Ruby vary between platforms, but much of the code in this book (particularly
in the earlier chapters) runs on all versions When we begin to look at more complex code, such as externallibraries and interfacing between Ruby and other systems, you should be prepared to make changes in yourcode or accept that you won’t have access to every feature However, if you’re using Windows, Linux, or Mac
OS X on an x86 architecture, almost everything will work as described in this book
Before you can start playing with Ruby, you need to get your computer to understandthe Ruby language by installing an implementation of Ruby on your system, which I’llcover first
To satisfy the majority of readers without referring to external documentation, I’mproviding full instructions for installing and using Ruby on Windows, Mac OS X, andLinux, along with links to Ruby implementations for other platforms In each case, I pro-vide instructions to check that the installation is successful before sending you on to theprogramming fun in Chapter 2
Windows
Ruby was initially designed for use under Unix and Unix-related operating systems such
as Linux, but Windows users have access to an excellent “one-click installer,” whichinstalls Ruby, a horde of extensions, a source code editor, and various documentation, in
“one click.” Ruby on Windows is as reliable and useful as it is on other operating systems,and Windows makes a good environment for developing Ruby programs
To get up and running as quickly as possible, follow these steps:
1. Open a Web browser and go to http://www.ruby-lang.org/en/downloads/
2. Scroll down to “Ruby on Windows,” about halfway down the page
Trang 363. In the “Ruby on Windows” section, you’ll see a few links for different versions ofRuby you can download for Windows Ideally you want to download the file at thelink that’s highest in the list that’s referred to as a “One-Click Installer.” At the time
of writing, this is version 1.8.5
4. Click the link you found in step 3 and save it to your desktop
5. Once download has completed, look on your desktop for the Ruby EXE file youjust downloaded, and double-click it to load the installer
6. If Windows gives you a “Security Error” box, click the “Run” button to give yourapproval
7. A typical installation program appears with some instructions On the initialscreen, click “Next.”
8. Work your way through the installation screens Leave the boxes checked to installthe text editors SciTE and FreeRIDE, and the Ruby package manager RubyGems(more on that in Chapter 7) Unless you have a specific reason not to, let theinstallation program install Ruby in its default location of c:\rubyand its defaultprogram group
9. Installation takes place when you see a stream of filenames flying up your screen
Wait several minutes for the installation process to complete and enjoy the view
There are a lot of files to install!
10. Installation is complete when the installation program says “Installation plete” and the “Next” button is clickable Click the “Next” button, then click
Com-“Finish” to exit the installation program
If Ruby installed correctly, congratulations! Go to the “Start” menu and then the grams” or “All Programs” menu There should be a Ruby program group that contains
“Pro-icons for FreeRIDE, SciTE, an uninstaller, and other bits and pieces To test that your
Ruby installation works correctly for Chapter 2, you need to load the program listed as
“fxri – Interactive Ruby Help & Console,” so click this entry and wait for the program to
load If the program loads successfully, you’ll see a screen that looks somewhat like that
in Figure 1-1
Trang 37Figure 1-1.The fxri interactive Ruby program
If fxri started properly, then Ruby is installed correctly Congratulations! Lastly, youneed to be familiar with running Ruby and its associated utilities from the command
prompt, so go to the “Start” menu, then “Run,” and type cmd into the box and click “OK”
(“Command Prompt” might also be in your “Programs” menu under “Accessories”) Youshould be presented with a command prompt, like that in Figure 1-2
Figure 1-2.The Microsoft Windows command prompt
Trang 38Throughout this book, commands that can be used at the command prompt will begiven This is because using a command prompt such as this is a standard technique in
operating systems such as Linux and OS X For example, in Chapter 7 we’ll look at
installing extra features (libraries) for Ruby, and the command prompt will be used for
this Therefore, it’s necessary for you to know how to access it and run programs
If you type irb at this prompt and press Enter, you should see something like the
following:
irb(main):001:0>
If you see the preceding line, everything is set up correctly, and you can type exit and
press Enter to be returned to the command prompt
Now you can move on to Chapter 2 and start to play with the Ruby language itself
Apple Mac OS X
Unlike Windows, most modern Apple machines running Mac OS X come with a version
of Ruby already installed, which means you can get started straight away Mac OS X
Panther (10.3.x) comes with Ruby 1.8.2 by default, and OS X Tiger (10.4.x) comes with
Ruby 1.8.4
■ Note It’s likely that OS X Leopard, due to be released in 2007, will come with the latest version of Ruby,
so if you’re running that operating system, unavailable at the time of writing, you might already be set to go!
Most of the code in this book works fine with Ruby 1.8.2 or higher, so if you’re ning Mac OS X Panther or Tiger, you don’t need to do anything special To find out which
run-version of OS X you’re running, click the “Apple” menu at the top left of your screen and
select “About This Mac.” If the version of OS X is later than 10.3, you should have Ruby
installed already
■ Tip If you’re using OS X Tiger (10.4.x), use Apple’s Software Update to upgrade to the latest version of
OS X, as Apple improved Ruby distribution included in OS X from version 10.4.6 onward Without this
upgrade, you might need to reinstall Ruby manually to get some extensions, such as Ruby on Rails, to
work correctly Although this isn’t a concern for the first two sections of this book, it could cause you some
confusion later on
Trang 39Testing for a Preinstalled Version of Ruby
If you’re using OS X Panther or OS X Tiger, you can check whether Ruby is installed byusing the Terminal application Double-click “Macintosh HD” (or whatever your harddrive is called) and go to the Applicationsfolder on your drive Once in Applications, go
to the Utilitiesfolder, where you’ll find an application called Terminal Double-click itsicon to start it If Terminal starts correctly, you’ll see a screen similar to that in Figure 1-3
Once you’re in the Terminal, you’re at what’s called the command prompt or shell.
You’re talking directly with your computer, in a technical sense, when you type The puter will execute the commands that you type immediately once you press Enter
com-Figure 1-3.The Mac OS X Terminal in OS X Tiger with a working Ruby installed and tested
To see if Ruby is installed, type the following at the command prompt from within
Terminal (be sure to press Enter afterward):
ruby –v
Trang 40If successful, you should see a result, as shown in Figure 1-3, that says what version
of Ruby you’re running (which should, ideally, be 1.8.2 or greater) If this works, try to run
the Ruby interactive interpreter called “irb” by typing the following at the command
prompt:
irb
If you get a result as shown in Figure 1-3, you’re ready to go and can move to Chapter 2
If you need to install a newer version of Ruby on OS X, continue to the next section
Installing Ruby on OS X
There are a few ways to install Ruby on OS X You can install from a prepackaged
installa-tion, by using a package manager such as Fink or DarwinPorts, or by compiling the Ruby
source directly If you already use Fink or DarwinPorts, then refer to their respective sites
for further information, but otherwise you’ll find it easier to use a prebuilt installation
and LightTPD These tools aren’t immediately useful, unless you’re planning to do some
Ruby on Rails development right away, but which you’ll be glad of by the end of this
book
Installing Ruby from Source on Mac OS X
Installing Ruby directly from source code on OS X is similar to Linux, so continue on to
the later Linux section entitled “Installing Ruby From Source Code.” Please note that
ver-sus installing a package such as Locomotive, when you install Ruby by source, all you get
is Ruby You need to install components such as Rails separately later
■ Note To compile the Ruby sources on OS X, you need to install the Xcode developer tools that come
with OS X