183_ruby_FC Ruby Developer's Guide (2002)
Ruby%20Developer's%20Guide%20-%20Robert%20Feldt
Ruby%20Developer's%20Guide%20(2002)
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 721
1 YEAR UPGRADE
BUYER PROTECTION PLAN
RUBY
D e v e l o p e r ’s
Guide
Everything You Need to Develop and Deliver Ruby Applications
• Complete Case Studies with Ready-to-Run Source Code and Full
Explanations
• Hundreds of Developing & Deploying Sidebars, Ruby FAQs, and Ruby
Sample Applications
• Complete Coverage of Ruby GUI Toolkits:Tk, GTK+, FOX, SWin/Vruby
Extensions, and Others
Robert Feldt
Lyle Johnson
Michael Neumann
Technical Editor
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page i
solutions@syngress.com
With more than 1,500,000 copies of our MCSE, MCSD, CompTIA, and Cisco
study guides in print, we continue to look for ways we can better serve the
information needs of our readers. One way we do that is by listening.
Readers like yourself have been telling us they want an Internet-based service that would extend and enhance the value of our books. Based on
reader feedback and our own strategic plan, we have created a Web site
that we hope will exceed your expectations.
Solutions@syngress.com is an interactive treasure trove of useful information focusing on our book topics and related technologies. The site
offers the following features:
■
One-year warranty against content obsolescence due to vendor
product upgrades. You can access online updates for any affected
chapters.
■
“Ask the Author” customer query forms that enable you to post
questions to our authors and editors.
■
Exclusive monthly mailings in which our experts provide answers to
reader queries and clear explanations of complex material.
■
Regularly updated links to sites specially selected by our editors for
readers desiring additional reliable information on key topics.
Best of all, the book you’re now holding is your key to this amazing site.
Just go to www.syngress.com/solutions, and keep this book handy when
you register to verify your purchase.
Thank you for giving us the opportunity to serve your needs. And be sure
to let us know if there’s anything else we can do to help you get the
maximum value from your investment. We’re listening.
www.syngress.com/solutions
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page ii
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page iii
1 YEAR UPGRADE
BUYER PROTECTION PLAN
Ruby
D e v e l o p e r ’s G u i d e
Robert Feldt
Lyle Johnson
Michael Neumann
Technical Editor
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page iv
Syngress Publishing, Inc., the author(s), and any person or firm involved in the writing, editing, or
production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results to be
obtained from the Work.
There is no guarantee of any kind, expressed or implied, regarding the Work or its contents.The Work is
sold AS IS and WITHOUT WARRANTY. You may have other legal rights, which vary from state to state.
In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other
incidental or consequential damages arising out from the Work or its contents. Because some states do not
allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation
may not apply to you.
You should always use reasonable care, including backup and other appropriate precautions, when working
with computers, networks, data, and files.
Syngress Media®, Syngress®,“Career Advancement Through Skill Enhancement®,” and “Ask the Author
UPDATE®,” are registered trademarks of Syngress Publishing, Inc. “Mission Critical™,”“Hack Proofing™,”
and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Syngress Publishing, Inc.
Brands and product names mentioned in this book are trademarks or service marks of their respective
companies.
KEY
001
002
003
004
005
006
007
008
009
010
SERIAL NUMBER
UJG4TFR2T5
AKJ7T4MAS4
VMERF3854N
SGD34BK9HN
85DFMU6N7H
NFG438GEM4
BAQ2HTR46T
CV5TR56KMR
83N5M4BT6Y
GT67FRWFEC
PUBLISHED BY
Syngress Publishing, Inc.
800 Hingham Street
Rockland, MA 02370
The Ruby Developer’s Guide
Copyright © 2002 by Syngress Publishing, Inc. All rights reserved. Printed in the United States of America.
Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or
distributed in any form or by any means, or stored in a database or retrieval system, without the prior
written permission of the publisher, with the exception that the program listings may be entered, stored,
and executed in a computer system, but they may not be reproduced for publication.
Printed in the United States of America
1 2 3 4 5 6 7 8 9 0
ISBN: 1-928994-64-4
Technical Editor: Michael Neumann
Cover Designer: Michael Kavish
Acquisitions Editor: Catherine B. Nolan
Page Layout and Art by: Reuben Kantor and Shannon Tozier
Developmental Editor: Kate Glennon
Copy Editor: Jesse Corbeil
Indexer: Robert Saigh
Distributed by Publishers Group West in the United States and Jaguar Book Group in Canada.
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page v
Acknowledgments
We would like to acknowledge the following people for their kindness and support
in making this book possible.
Richard Kristof and Duncan Anderson of Global Knowledge, for their generous
access to the IT industry’s best courses, instructors, and training facilities.
Ralph Troupe, Rhonda St. John, and the team at Callisma for their invaluable insight
into the challenges of designing, deploying and supporting world-class enterprise
networks.
Karen Cross, Lance Tilford, Meaghan Cunningham, Kim Wylie, Harry Kirchner,
Kevin Votel, Kent Anderson, and Frida Yara of Publishers Group West for sharing
their incredible marketing experience and expertise.
Mary Ging, Caroline Hird, Simon Beale, Caroline Wheeler,Victoria Fuller, Jonathan
Bunkell, and Klaus Beran of Harcourt International for making certain that our
vision remains worldwide in scope.
Annabel Dent of Harcourt Australia for all her help.
David Buckland,Wendi Wong, Marie Chieng, Lucy Chong, Leslie Lim, Audrey Gan,
and Joseph Chan of Transquest Publishers for the enthusiasm with which they receive
our books.
Kwon Sung June at Acorn Publishing for his support.
Ethan Atkin at Cranbury International for his help in expanding the Syngress
program.
Jackie Gross, Gayle Vocey, Alexia Penny, Anik Robitaille, Craig Siddall, Darlene
Morrow, Iolanda Miller, Jane Mackay, and Marie Skelly at Jackie Gross & Associates
for all their help and enthusiasm representing our product in Canada.
Lois Fraser, Connie McMenemy, and the rest of the great folks at Jaguar Book Group
for their help with distribution of Syngress books in Canada.
v
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page vi
Technical Editor’s
Acknowledgements
I’d like to thank the Syngress staff for their support, and John Small, who
encouraged me in overseeing the writing of this book. I’d like to thank
Matz for creating such a wonderful language; Dave and Andy for two
really great books about programming in general, and Ruby; Kentaro
Goto for his tutorial that directed me three years ago to Ruby; and
Hiroshi Nakamura for many valuable comments and explanations about
SOAP4R. Finally, thank you to the team of Merlin.zwo for being patient
with me, as well as to the whole Ruby community for letting me participate in such a great development.
vi
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page vii
Contributors
Jason Wong is the Chief Executive Officer of ionami design, a Web
development and design firm headquartered in Berkeley, CA. His responsibilities include developing and maintaining client relationships, project
management, application development and support, and operations management. Previously, he managed all aspects of 3dfxgamers.com, the 3dfx
interactive community Web site. Jason holds a bachelor’s degree from the
University of California at Berkeley. He would like to thank Joyce,Ted
and Tim, and his parents for all their support.
Lyle Johnson is a Software Team Leader at ResGen, Invitrogen
Corporation in Huntsville, AL. Prior to his employment at ResGen, Lyle
served as Group Leader for Graphical User Interface Development at
CFD Research Corporation. Lyle has worked primarily in commercial
software development for computational fluid dynamics and bioinformatics applications, but has also managed and contributed to a number of
open-source software projects.
Lyle holds a bachelor’s degree in Aerospace Engineering from Auburn
University and a master’s of Science degree in Aerospace Engineering
from the Georgia Institute of Technology. He currently lives in Madison,
AL with his wife, Denise.
Jonothon Ortiz is Vice President of Xnext, Inc. in Winter Haven, FL.
Xnext, Inc. is a small, privately owned company that develops Web sites
and applications for prestigious companies such as the New York Times
Company. Jonothon is the head of the programming department and
works together with the CEO on all company projects to ensure the best
possible solution. Jonothon lives with his wife, Carla, in Lakeland, FL.
Robert Feldt is a Software Engineering Researcher at Chalmers
University of Technology in Gothenburg, Sweden. His professional
interest is in how to produce robust, reliable software. Robert’s research
vii
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page viii
focuses on what can be learned from applying the complex but robust
systems found in nature to tools and methods for developing and testing
software. Robert also teaches courses on software engineering to students
in the Computer Science and Computer Engineering programs at
Chalmers University.
Robert holds a master’s degree from Chalmers University and is a
member of the IEEE. He has previously worked as a consultant software
engineer. He programs mostly in C, Haskell, and Ruby and uses Ruby
frequently in his research since its dynamic nature allows him to easily test
new ideas. He is working on a number of larger Ruby projects, including
the Rockit compiler construction toolkit and the RubyVM project, to
build a set of plug-and-play components for assembling Ruby virtual
machines.
Robert currently resides in Gothenburg, Sweden with his wife,
Mirjana, and daughter, Ebba. He wants to acknowledge them for their
support and love.
Stephen Legrand (Ph.D.) has both an academic and commercial background. He was a post-doctoral fellow at MIT and has lectured both
mathematical and computer science related subjects at the university level.
He has taught graduate and undergraduate courses in such diverse areas as
assembly language, automata theory, computability, discrete mathematics,
computer graphics, and in mathematical subjects such as differential equations, advanced calculus, financial mathematics, and model theory. In addition, Stephen has over 10 years of software development expertise in such
areas as fixed income derivatives, interest rate modeling, artificial intelligence, and telecommunications. He has authored computer graphics
engines, computer chess games, option pricing engines, cellular propagation models, and workflow management systems. He is currently consulting on the IRROS project and on J2EE-related technologies in the
Washington, DC area.
viii
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page ix
Technical Editor and Contributor
Michael Neumann is a Database and Software Developer for
Merlin.zwo InfoDesign GmbH in Germany (near Stuttgart). He is also
studying computer science at the University of Karlsruhe. Merlin.zwo
develops large-scale database applications based on Oracle products.
With more than 10 years of experience in software development,
Michael has specialized in many different domains, from system-near
programming, administration of Unix systems, and database development with several RDBMSs, to OOA/OOD techniques, and design and
implementation of distributed and parallel applications. One of his
greatest interests lies is the design principles of programming languages.
Before he was employed at Merlin.zwo, he was a Database/Web
Developer and Principal of Page-Store.
ix
183_Ruby_FM.qxd
1/7/02
4:04 PM
Page x
183RubyToC.qxd
1/7/02
4:31 PM
Page xi
Contents
Foreword
■
Ruby’s design
philosophy is known
as the Principle of
Least Surprise. That
means that Ruby
works the way that
you expect it to
work. The more you
develop with Ruby,
the more you’re
going to realize that
you’re spending
time producing
code—real code
which works, is
readable, and solves
the problems at
hand.
Chapter 1
Booting Ruby
Introduction
An Overview of Ruby
Installing Ruby and its Tools
Installing Ruby on Unix
Installing Ruby from Source Code
Installing from Packages
Installing Ruby on a Windows System
Installing Applications and Libraries
from RAA
IDE and Editor Support in Ruby
Emacs
VIM
Other Editors
RubyWin
Ruby Development Environment (RDE)
Additional Tools a Rubyist Must Have
Ruby Interactive (Ri)
Interactive Ruby (IRb)
Debugging Ruby Applications
with debug.rb
A Short Syntax Style Guide
Using Comments
Naming
Iterators
Indentation, Spacing, Parentheses
xxiii
1
2
2
3
5
5
7
7
8
10
11
12
12
12
13
13
14
15
17
22
22
23
24
24
xi
183RubyToC.qxd
xii
1/7/02
4:31 PM
Page xii
Contents
Dangerous Ruby
Local Variables versus Methods
More Whitespace Issues
Block Local Variables
Comparing Ruby
Java
Perl
Language Constructs
Object-Oriented Programming
Access Control
Arrays and Hashes
Hashes
Iterators
Convincing Management to Use Ruby
Summary
Solutions Fast Track
Frequently Asked Questions
25
25
25
26
26
26
32
32
33
34
35
36
36
37
39
39
41
Chapter 2
GUI Toolkits for Ruby
43
Introduction
44
Using this Book’s Sample Applications
45
Using the Standard Ruby GUI:Tk
46
Obtaining Tk
46
Ruby/Tk Basics
47
Creating Responses to Tk’s Callbacks
and Events
48
Working with Ruby/Tk’s Layout Managers
50
Ruby/Tk Sample Application
54
Using the SpecTcl GUI Builder
67
Obtaining Tk Extensions:Tix and BLT
68
Using the GTK+ Toolkit
68
Obtaining Ruby/GTK
69
Ruby/GTK Basics
70
Programming Signals and Signal Handlers
71
Working with Ruby/GTK’s Layout Managers 72
Ruby/GTK Sample Application
76
183RubyToC.qxd
1/7/02
4:31 PM
Page xiii
Contents
Master the Grid Layout
Manager
Using the Glade GUI Builder
Using the FOX Toolkit
Obtaining FOX and FXRuby
FXRuby Basics
Targets and Messages
Working with FOX’s Layout Managers
Fox Sample Application
Using the SWin/VRuby Extensions
Obtaining SWin and VRuby
VRuby Library Basics
Layout Managers
Event Handling
VRuby Sample Application
Other GUI Toolkits
Choosing a GUI Toolkit
Summary
Solutions Fast Track
Frequently Asked Questions
Chapter 3
Accessing Databases with Ruby
Introduction
Accessing Databases with Ruby/DBI
Obtaining and Installing Ruby/DBI
Programming with Ruby/DBI
Understanding Ruby/DBI Architecture
and Terminology
Connecting to Databases
Using Driver URLs and
Datasource Names
Preparing and Executing SQL Statements
Fetching the Result
Performing Transactions
Handling Errors
Tracing the Execution of
DBI Applications
Accessing Metadata
xiii
87
90
90
91
93
95
99
111
112
112
116
118
120
127
128
129
130
132
135
136
136
140
141
143
144
146
148
156
162
164
166
169
183RubyToC.qxd
xiv
1/7/02
4:31 PM
Page xiv
Contents
Answers to Your Ruby
Database Questions
Q: Using Ruby/DBI, I
have set the tracing
level to 2 and
output to standard
error, but nothing
happened. What’s
wrong?
A: You may have
forgotten to require
the dbi/trace file at
the top of your
program.
Using Driver-specific Functions
and Attributes
Accessing Databases Remotely Using
DBD::Proxy
Copying Table Data between
Different Databases
Getting Binary Objects Out of a Database
Transforming SQL-query Results to XML
Accessing Databases with Ruby/ODBC
Accessing LDAP Directories with Ruby/LDAP
Using Ruby/LDAP
Adding an LDAP Entry
Modifying an LDAP Entry
Deleting an LDAP Entry
Modifying the Distinguished Name
Performing a Search
Handling Errors
Utilizing Other Storage Solutions
Reading and Writing Comma-Separated
Value Files
Using Berkeley DBM-file Databases
Using the Berkeley DB Interface BDB
Storing Ruby Objects in a Relational
Database
Summary
Solutions Fast Track
Frequently Asked Questions
Chapter 4
XML and Ruby
Introduction
Why XML?
Making XML Manageable
Validation though DTD
Validating With XML-Schemas
XPath
XML Parser Architectures and APIs
171
174
175
176
179
190
195
195
196
196
197
197
197
199
199
199
200
201
205
208
208
209
211
212
212
214
214
216
218
218
183RubyToC.qxd
1/7/02
4:31 PM
Page xv
Contents
REXML has the following
advantages:
1. It is written 100
percent in Ruby.
2. It can be used for
both SAX and DOM
parsing.
3. It is small—
approximately 1845
lines of code.
4. Methods and classes
are in easy-tounderstand English.
Parsing and Creating XML in Ruby
Shared Code for Examples
Defining and Implementing Classes
Host and Port
Defining and Implementing the
Report Class
Using XMLParser
Installing XMLParser on Unix
Using NQXML
Installing NQXML
Using REXML
Using XSLT in Ruby
Ruby-Sablotron
XSLT4R
Summary
Solutions Fast Track
Frequently Asked Questions
Chapter 5
Web Services and Distributed Ruby
Introduction
Using XML-RPC for Ruby
Obtaining and Installing xmlrpc4r
Configuring xmlrpc4r
Writing XML-RPC Clients
Using the MultiCall Extension
Introspecting XML-RPC Servers
Writing XML-RPC Servers
Project: A File Upload Service
XML-RPC Datatypes
User-defined Datatypes
Dumping and Loading XML-RPC Messages
Communicating with Python’s xmlrpclib
Securing XML-RPC Services
Client-side Support
Server-side Support
Performance Comparisons
xv
221
228
229
230
234
234
240
241
251
254
254
254
256
257
258
261
262
262
263
263
264
268
268
270
274
276
278
278
279
280
280
281
281
183RubyToC.qxd
xvi
1/7/02
4:31 PM
Page xvi
Contents
Monitoring TCP/IP Based
Services
We can monitor Web
services, or any TCP/IPbased client and server, by
using a very simple
monitor application that
comes with XML-RPC for
Ruby or TCPSocketPipe
(available from the Ruby
Application Archive
[RAA]).
Using SOAP for Ruby
Obtaining and Installing SOAP4R
Writing SOAP4R Client and Server
Applications
Choosing an XML Parser
Writing SOAP4R Clients
Writing SOAP4R Services
SOAP Datatypes and Type-Conversion
Creating Multi-dimensional or
Typed SOAP Arrays
Creating User-defined Datatypes
Changing the Default Type-Mapping
Using SOAP as Marshalling Format
Project: A SOAP Authentification Server
Using Distributed Ruby
A Name Server for DRb
Using DRb to Speed Up CGI Scripts
Using Rinda and Distributed TupleSpaces
Load-Balancing
Security Considerations
Summary
Solutions Fast Track
Frequently Asked Questions
Chapter 6
WWW and Networking with Ruby
Introduction
Connecting to the Web with Ruby
Low-Level Functions:The Socket Class
High-Level Functions:The Net Class
POP/SMTP
HTTP
FTP
Telnet
Writing a Server in Ruby
Models of Server Architectures
Basic Web Servers Using Ruby
284
286
286
288
289
298
303
306
306
308
310
313
321
324
325
328
331
333
336
336
337
339
340
340
340
341
341
342
342
344
345
345
347
183RubyToC.qxd
1/7/02
4:31 PM
Page xvii
Contents
Dynamically Generating
XML with eruby
You can also generate
XML with eruby and
mod_ruby. This is useful,
for example, if you want
to deliver XML to the
browser, which then (on
the client-side) invokes an
XSLT script to transform it
to HTML. Not many
browsers support this; in
fact only Microsoft’s
Internet Explorer can do
this for certain.
Using Ruby on the Web
Generating HTML with Ruby
Ruby HTML Code Generation
Ruby CGI HTML Generation
Scripting With Ruby Using eruby and ERb
Templating With Ruby
Using the HTML/Template Extension
Using Ruby-tmpl
Putting It All Together
Implementing an Online Shopping Application
Designing the Data Model
The Database Access Layer
Initializing the Database
Developing the Web Interface
Improving the Online Shop
Using mod_ruby and eruby
Installing and Configuring mod_ruby
Using mod_ruby and eruby in the
Online Shop Example
Dynamically Generating XML with eruby
Displaying RSS News Channels
Installing and Configuring IOWA
Using IOWA for the Online Shop Example
Implementing a TreeView Component
Summary
Solutions Fast Track
Frequently Asked Questions
Chapter 7
Miscellaneous Libraries and Tools
Introduction
Graphics Programming in Ruby
Using OpenGL in Ruby
Defining the Goal and the Strategy
Starting with a Sample Program
Creating Multiple Curves
Generating Diagrams with GD::Graph
xvii
355
356
356
357
358
359
359
361
361
361
362
366
369
372
379
383
384
386
395
396
400
404
410
420
420
422
423
424
424
425
425
425
434
441
183RubyToC.qxd
xviii
1/7/02
4:31 PM
Page xviii
Contents
NOTE
There are basically
two types of libraries,
those written in pure
Ruby, and those that
are C extensions to
Ruby. Generally, pure
Ruby extensions only
require being on the
search path. The C
extensions to Ruby
are usually installed
by unzipping or
untarring, and then at
the command line
typing ruby
extconf.rb, which
builds a Makefile.
Mathematical Programming in Ruby
Using the NArray Library
Using the BigFloat Library
Using the Polynomial Library
Using the Algebra Extension
Working with Polynomials
Working with Matrices
Exploring C/S Data-Structure Tools
Using the BinaryTree Extension
Using the BitVector Extension
Using Random Numbers, Genetic Algorithms,
and Neural Nets
Working with a Random-Number Generator
Genetic Programming in Ruby
Neural Nets
Working with Ruby and Windows
Using ActiveScript in Ruby
Using WinOLE in Ruby
Using OOP-Related Tools
Using the EachDelegator Library
Using the Preserved, Forwardable, and
Finalize Modules
Using Text-Processing, Date, and Calendar Tools
Using the Soundex Extension
Using the Date2 and Date3 Extensions
Using the Calendar Extension
Using Language Bindings
Using JRuby
Ruby Calling Java
Java Calling Ruby
Using the Ruby/Python Extension
Summary
Solutions Fast Track
Frequently Asked Questions
442
442
447
448
454
454
455
460
460
464
467
467
468
475
482
482
484
488
488
489
493
493
494
496
498
498
499
503
507
511
511
513
183RubyToC.qxd
1/7/02
4:31 PM
Page xix
Contents
A Process for Program
Optimization
1. Question the need!
2. Look at the big
picture!
3. Find the hot-spots!
4. Check structure and
data!
5. Dig deep!
6. Know your Ruby
environment and
use it wisely.
xix
Chapter 8
Profiling and Performance Tuning
515
Introduction
516
Analyzing the Complexity of Algorithms
517
Comparing Algorithms
520
The Different “Ordos”
522
Average and Worst-case Complexity
523
Improving Performance by Profiling
525
Profiling Using profile.rb
529
How the Standard Profiler Works
531
Drawbacks with the Standard Profiler
533
Profiling Using RbProf in AspectR
533
Understanding AOP and AspectR
539
Using AspectR
540
How AspectR Works
542
Comparing AspectR and AspectJ
543
Comparing the Speed of Ruby Constructs
544
Adding Elements to Arrays
546
Concatenating Strings
549
Predeclaring Variables
551
Iterating Over Array Elements
552
Iterating Over Array Elements with
an Index
553
Destructive versus Non-destructive Methods 554
Accessing the First Array Element
555
Creating Arrays and Hashes
556
Calling Methods and Proc Objects
557
Further Performance Enhancements
558
Caching Results
558
When Not To Use Result Caching
560
How Memoize Works
561
Disabling the Garbage Collector
561
Writing a C Extension
563
Summary
565
Solutions Fast Track
566
Frequently Asked Questions
567
183RubyToC.qxd
xx
1/7/02
4:31 PM
Page xx
Contents
Comparing Racc and
Rockit
■
■
■
■
Racc is more stable
than Rockit.
The Bison algorithms
used in Racc have
been well studied
since the 1970’s.
Rockit’s parsers are
first-class objects in
Ruby and ordinary
Ruby code can be
used when defining
them, so you have
the power of Ruby
at your fingertips
while writing your
grammars.
Racc’s grammar
cannot use
repetition operators
(+, * and ?) so you
will have to rewrite
your grammar in a
form that Racc can
understand. Rockit
can use repetitions
operators. It can also
be used to parse
context-sensitive
constructs.
Chapter 9
Parser Generators
569
Introduction
570
Creating the Parsing Library
of your Dreams
571
Why Not Use Regexps?
576
Representing Recovered Structures
with Abstract Syntax Trees
577
Parsing in Ruby with Rockit
581
Deviations from Parsing Library of
Our Dreams
582
Using Rockit as a Parser Generator
587
Case-Insensitive Parsing
589
Customizing Your Parser
589
Parser Generators
590
Parser Combinators
591
Parser Transformers
593
Error-related Building Blocks
595
Parsing in Ruby with Racc
596
Writing the Grammar Rules
599
Writing a Lexical Analyzer for Use
with Racc
600
Invoking the Racc Command Line Tool 605
Building Abstract Syntax Trees with
Racc-generated Parsers
606
Comparing Racc and Rockit
609
Summary
610
Solutions Fast Track
610
Frequently Asked Questions
611
Chapter 10
Extending and Embedding Ruby
Introduction
Writing C/C++ Extensions
Working with Datatype Conversions
Working with Objects
Working with Numbers
613
614
615
618
618
619
183RubyToC.qxd
1/7/02
4:31 PM
Page xxi
Contents
Writing C/C++
Extensions
■
■
Ruby alone may not
provide the speed or
functionality
required for your
Ruby applications.
When this is true,
you can write
extension modules
in C or C++ that
look like regular
modules to the Ruby
interpreter.
Ruby’s C API
provides a wide
variety of functions
that assist extension
writers in defining
modules, classes,
and constants, and
converting back and
forth between C and
Ruby datatypes.
Working with Strings
Working with Arrays
Working with Hashes
Working with C/C++ Data Wrappers
Implementing Methods
An Example: K-D Trees
Ruby Implementation of the K-D Tree
Compiling the C Implementation
of the K-D Tree
Comparing the Results
Using SWIG
A Simple SWIG Example in C
Using SWIG With C++
Choosing SWIG
Embedding Ruby
Configuring Extensions with Mkmf
Summary
Solutions Fast Track
Frequently Asked Questions
Index
xxi
620
623
627
627
632
635
636
656
657
658
658
661
666
666
671
674
674
676
677
183RubyToC.qxd
1/7/02
4:31 PM
Page xxii
183Ruby_fore.qxd
1/7/02
4:32 PM
Page xxiii
Foreword
If you define efficiency as the ruler for the success of a language, Ruby should be
one of the very first languages to come to mind.The introduction of Ruby to the
programming world has astounded developers with its ability to simply make programming fun again. Ruby frees programmers to concentrate on the problem at
hand, creating fewer obstacles than other languages. In Ruby, ideas flow directly into
the code.
Even though Ruby is very effective, there’s still a deficit of written documentation and tutorials about deploying it for real world applications. Deployment usually
requires knowledge in one or more of these fields:
■
Graphical User Interfaces (GUIs)
■
Distributed Computing and Networking
■
Accessing Databases
■
Processing and Transforming XML
■
Text-Processing and Parsing
■
WWW-based Applications
■
Profiling and Performance Tuning
■
Connecting with other Languages, Extending, and Embedding
This is why we wrote this book.We hope it helps you become more a more productive programmer with Ruby—and that you have fun reading it and performing
the examples.
xxiii
183Ruby_fore.qxd
xxiv
1/7/02
4:32 PM
Page xxiv
Foreword
Why Ruby?
With its clean object-oriented (OO) programming model (everything is an object) and
its solid foundation, it is one of the simplest-to-use and most powerful OO languages. Ruby unifies many positive features of other languages, for instance :
■
Strong dynamic typing; no need to declare variables
■
Exceptions
■
Closures, code-blocks, and iterators as found in Smalltalk, Sather, or CLU
■
A powerful yet easy-to-use object-oriented class library, designed with the
“principle of least surprise” in mind, and with several design patterns
included (for example, Delegator, Observer,Visitor, and Singleton)
■
A comfortable, familiar syntax, which is a mixture of elements from C++,
Eiffel, Perl, and Python.
■
Arbitrary precise integers with automatic conversion to and from
fixed-sized integers
■
Mark-and-sweep Garbage Collectors and a simple C-API for extending and
embedding Ruby
■
Lightweight threads and continuations
■
Built-in regular expressions
Sweetened with a healthy amount of syntax, Ruby applications have the potential
of being more concise and condensed than (or at least the same length as) an equivalent application written in Perl (or Python), as well as being easier to read, maintain,
and learn—not to mention that it’s much more fun to program!.
Who Should Read This Book?
This book will not serve as an introduction to Ruby, but more as an extension of
existing books about Ruby programming, so we expect that the reader has gathered
a certain degree of knowledge and experience with Ruby before reading this.
Nevertheless, newcomers to Ruby who have even a basic understanding of the
language may find it very useful to fortify their knowledge by studying many of the
examples. Learning by doing is the best way to really learn a language. In addition, of
course, readers of any level will be aided in exercising their natural interests in dis-
www.syngress.com
183Ruby_fore.qxd
1/7/02
4:32 PM
Page xxv
Foreword
xxv
covering new ideas and entertaining different and creative ways to solve existing
problems!
Content of this Book
Ruby is a rapidly evolving language. Every few months, new projects are started and
existing ones are being shaped and improved; we have accepted this challenge by
providing a snapshot of the current state of development and encouraging you to
look into the continuing evolution.
Chapter 1: Booting Ruby provides the basics of getting started by explaining
Ruby syntax, and about working with applications and editors.
Chapter 2: GUI Toolkits for Ruby develops a sample application (a XML
viewer) with four different GUI toolkits available for Ruby:Tk, Gtk, Fox,
and VRuby.
Chapter 3: Accessing Databases with Ruby introduces you to programming
with Ruby/DBI, a unique database-independent interface for accessing
many relational databases; it covers Ruby/ODBC as well as other data
storage solutions like CSV or Berkeley DBM-like file databases.
Chapter 4: XML and Ruby takes a look at some of the more popular
parsing options available for Ruby and XML, including SAX and DOM,
and open source parsers XMLParser, NQXML, and REXML.
Chapter 5: Web Services and Distributed Ruby describes and explains how to
use the two XML-based communication protocols (XML-RPC and SOAP)
from Ruby as well as how to connect two or more Ruby applications across
a network using Distributed Ruby (DRb).
Chapter 6: WWW and Networking with Ruby develops a Web-based,
database-driven online-shop application, comparing a CGI/FastCGI
approach with the utilization of mod_ruby and eruby, and using Interpreted
Objects for Web Applications (IOWA), Ruby’s powerful application server.
Chapter 7: Miscellaneous Libraries and Tools explores Ruby extensions, which
are either written in pure Ruby or are Ruby wrappers around C code, and
compares them for ease of install, easy to read, and easy to customization
and development.
www.syngress.com
183Ruby_fore.qxd
xxvi
1/7/02
4:32 PM
Page xxvi
Foreword
Chapter 8: Profiling and Performance Tuning examines how to improve performance by looking at your overall algorithm, and how to analyze its complexity by using the ordo notation as a tool or by using a profiler such as
RbProf; other solutions include result caching.
Chapter 9: Parser Generators looks at the options and benefits in producing a
parser by writing it manually versus using a parser generator that will generate a parser from the grammar.
Chapter 10: Extending and Embedding Ruby explains how and why you
might write a Ruby extension module in C/C++.
About the Web Site
The Syngress Solutions Web Site contains the code files that are used in specific
chapters of this book.The code files for each chapter are located in a “chXX” directory. For example, the files for Chapter 6 are in ch06. Any further directory structure
depends on the projects that are presented within the chapter.
It will be extremely useful for you to have the applications and tools included in
these files on hand, however, because many of them are still evolving, within the
chapters you will be able to find mention of other online sources, such as the Ruby
Application Archive, from which you can obtain updates to the very latest versions.
Look for this icon to locate the code files
that will be included on our Web site.
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 1
Chapter 1
Booting
Ruby
Solutions in this chapter:
■
An Overview of Ruby
■
Installing Ruby and its Tools
■
A Short Syntax Style Guide
■
Dangerous Ruby
■
Comparing Ruby
■
Convincing Management to Use Ruby
; Summary
; Solutions Fast Track
; Frequently Asked Questions
1
183RubyC01.qxd
2
1/4/02
3:50 PM
Page 2
Chapter 1 • Booting Ruby
Introduction
Programming should be like driving a good car: Buttons are clearly labeled and
easy to reach; you’re comfortable as soon as you get inside; there are always a
couple of nuances, but soon, the machine becomes an extension of yourself;
you zig, you zag, and you always get where you’re going. Welcome to the
Porsche of programming languages. Perhaps you come from the world of C++
or Java, but would like something easier on the eyes and the fingers. Perhaps
you program in Perl, and would like to avoid bending over backwards for reusability. Congratulations, you’ve found Ruby, an object-oriented language
that’s easy to write and easy to read.
Ruby usage is growing daily. For instance, Ruby is spreading like wildfire in
Japan, ever since Yukihiro ‘Matz’ Matsumoto’s posting of version 0.95 on Japanese
domestic newsgroups.There, Ruby surpasses Python in popularity. In 2000, technical references began introducing and championing Ruby to the Englishspeaking markets as an alternative programming language, and Ruby growth
became an international phenomenon. By adding Ruby to your language repository, you join a burgeoning rank of developers that know an easier, faster, and
more enjoyable way to get the job done.
An Overview of Ruby
Ruby’s design philosophy is known as the Principle of Least Surprise.That means
that Ruby works the way that you expect it to work.The more you develop with
Ruby, the more you’re going to realize that you’re spending time producing code.
Real code, which works, is readable, and solves the problems at hand. Less time in
the debugger, less time spent in setup—hence, the Principle of Least Surprise.
Ruby, the vast majority of the time, works intuitively.
From this design philosophy comes a pure, powerful and simple object-oriented programming language.We like to believe that Ruby takes many of the
best features from other languages and blends them together very, very well.
Ruby derives much of its object-oriented system from Smalltalk: All data
structures are objects, allowing you to perform methods on them.
Furthermore, you can add methods to a class or instance during runtime. Like
Java or Smalltalk, Ruby features single inheritance. Because multiple inheritance
sometimes leads to an almost mystic inheritance determination, single-inheritance reduces the chance for pilot error. If you miss multiple inheritance, you
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 3
Booting Ruby • Chapter 1
can import methods from multiple classes using modules, also known as
mixins.
The open source nature of Ruby makes it free for anyone’s use. Because of
this, you are free to modify it. Many people have taken license to make Ruby a
cross-platform language, so while primary development occurs on Unix, Ruby
ports exist for a number of different platforms, including BeOS, DOS, MacOS,
Win32, and many flavors of Unix, including Solaris and FreeBSD. Furthermore,
Ruby’s Application Programming Interface (API) is written in C.This enables
straightforward extension writing with C.
Ruby’s dynamic typing saves time and creates a more flexible design structure.
In a static language, such as Java or C++, you must declare your variable types,
which requires setup time. Ruby is smart enough to know “hello” is a string, 2.0
could be a double, and 2 is an integer. Furthermore, Ruby doesn’t require
explicit declaration of its internal representation. Fixnum, which is an integer
type for small numbers, automatically converts to Bignum when it gets sufficiently large. Furthermore, dynamic typing allows for design changes without
changing types across the program, as the interpreter makes type decisions
during runtime.
An automatic mark-and-sweep garbage collector cleans all Ruby objects
without needing to maintain a reference count; you won’t have memory leaks,
and this results in fewer crashes.With languages such as C++, you have to release
allocated memory. However, Ruby flushes dynamically-allocated storage through
program execution, and has periods set to reclaim memory.
Installing Ruby and its Tools
Your first step into Ruby starts with its home on the Web, which is at
www.ruby-lang.org (Figure 1.1).You’ll find the source tarball for stable and
development versions, various links to documentation, commentary, the Ruby
Application Archive (RAA), and more.You can download and install Ruby in less
than 15 minutes. Some tools will be more or less complex, depending on size and
their individual dependencies on other files. MySQL and PostgreSQL interfaces
will require their respective databases, for instance.
Andrew Hunt and Dave Thomas (known as the Pragmatic Programmers) maintain www.rubycentral.com (Figure 1.2).This site contains the binary installation
of Ruby, various articles, links, an FAQ and an online version of their book,
Programming Ruby: A Pragmatic Programmer’s Guide.
www.syngress.com
3
183RubyC01.qxd
4
1/4/02
3:50 PM
Page 4
Chapter 1 • Booting Ruby
Figure 1.1 The Ruby Language Home Page
Figure 1.2 The RubyCentral Home Page
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 5
Booting Ruby • Chapter 1
Installing Ruby on Unix
Adding Ruby to your Unix development toolbox is a snap. In the following sections, we’ll show you how to download Ruby through various distribution
mechanisms, and take you through the installation procedure. If you install anything through source, this is about as easy as it gets.
Installing Ruby from Source Code
For those of you that like to play with the latest stable and development versions,
get the latest code drop using the Concurrent Versioning System (CVS), File
Transfer Protocol (FTP), or by downloading it from Ruby’s homepage. As the
source uses less than 1 megabyte of hard drive space, you can get the Ruby
source in less than five minutes over a 56k modem.
FTP Installation
FTP requires a client application. Standard distributions come with an FTP
client installed.The commands used in a Unix FTP installation can be seen in
Figure 1.3.
Figure 1.3 Unix FTP (or Windows DOS-based FTP) Commands
ftp ftp.ruby-lang.org
User: anonymous
Password: youremail@yourdomainname
binary
cd pub/ruby
ls
get ruby-x.tar.gz (latest version)
While some versions of Windows come with an FTP client, we suggest
downloading Bullet Proof FTP (shareware) or LeechFTP (freeware) from
www.download.com.
1. Set up your FTP client to log into ftp.ruby-lang.org, User: anonymous,
Password: youremail@yourdomainname.
2. Change to directory pub/ruby.
3. Choose the latest version of Ruby for download: ruby-x.tar.gz (make
sure you download it as binary).
www.syngress.com
5
183RubyC01.qxd
6
1/4/02
3:50 PM
Page 6
Chapter 1 • Booting Ruby
After having downloaded the Ruby archive, unpack it and change into the
newly created directory:
tar -xvzf ruby-1.6.6.tgz
cd ruby-1.6.6
Then configure and compile it:
./configure
make
Finally, install it with:
su -l root
# become a root user
make install
exit
# become the original user again
After installation, see if you can start Ruby by issuing the following command
on the command-line:
ruby --version
This should output the version of the installed Ruby interpreter; on my
system this is revealed as a Unix version.
ruby 1.6.4 (2001-06-04) [i386-netbsd]
If you have problems with the Ruby interpreter or one of its libraries, write
an e-mail to Ruby’s mailing list and include this version output.
CVS Installation
By using CVS, you can get the latest and greatest version of Ruby. Be forewarned
that this version is usually not stable, as it is a development version.
You can use either the Web or a CVS client.To access CVS via the Web, go
to www.ruby-lang.org/cgi-bin/cvsweb.cgi/ruby. At the bottom of the page, there
is a link to download the directory as a tarball or Zip archive. Download that
directory, as well as the doc, ext, lib, misc, sample, and win32 directories. Proceed
with the downloaded tarballs in the same way as for the FTP installation except
that you have to execute autoconf just before executing ./configure.
To use a CVS client, check out the development version using the following
two commands:
cvs -d :pserver:anonymous@cvs.ruby-lang.org:/src login
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 7
Booting Ruby • Chapter 1
(Logging in to anonymous@cvs.ruby-lang.org)
CVS password: anonymous
cvs -z4 -d :pserver:anonymous@cvs.ruby-lang.org:/src co ruby
After that, change into the ruby directory in which CVS downloaded all files,
and issue the autoconf command.Then proceed the same way as for the FTP
installation.
Installing from Packages
Some prefer to do source installations, as that offers access to the latest source;
and occasionally, packages get a little sticky with where directories are placed and
such.That being said, there’s no easier way to get Ruby onto your system than
through a ready-made package.
Red Hat 7.2 currently ships with Ruby 1.6.4.You can download a Red Hat
distribution from ftp.redhat.com.The rpm –i rubyx.x. command installs
without a hitch.
FreeBSD and NetBSD ports (OpenBSD currently has only Ruby 1.4.6 in its
port collection) of the newest Ruby interpreter are available through their port
collections, as well as many other Ruby related packages.
The current stable branch of Debian Linux contains an older version of
Ruby (currently 1.4.3), and will install and configure that version for you.Testing
branches currently contain 1.6.3, and unstable versions will offer you the latest
installation.
Installing Ruby on a Windows System
On Windows, the easiest possible installation option is to use the Pragmatic
Programmer’s binary release.
Grab the latest ruby-x.exe file at www.rubycentral.com/downloads/
ruby-install.html.This double-click installation includes the Ruby interpreter, a
required Cygwin DLL, documentation, and Tk and FOX support. If you run
Windows 9x or above, we highly recommend using this package. It makes installation as simple as clicking the Next button a few times and you will be up and
running with Ruby in minutes.
If you use Windows and absolutely, positively must have the latest version, the
install process requires a few extra steps.You must first download Cygwin, which
is a Unix environment for Windows.
1. Download Cygwin: Go to http://sources.redhat.com/cygwin and click
Install Cygwin Now.The setup process will give you a number of files
www.syngress.com
7
183RubyC01.qxd
8
1/4/02
3:50 PM
Page 8
Chapter 1 • Booting Ruby
to download.You should install everything, just in case. For this installation you should have copious amounts of hard disk space, but if you
don’t, you can remove files at your discretion (you must keep bash, GCC,
and the basic Cygwin files).
2. Download the Ruby source via FTP or CVS.
3. Create an instance of Cygwin.
4. Change to the Ruby source directory where you’ve unpacked the Ruby
sources.
5. Use standard Unix compile, configure, and install commands:
./configure
make
make install
If you use Windows 9x, add the following lines to your c:\autoexec.bat:
set PATH="D:\(ruby install directory)\bin;%PATH%"
Windows NT/2000 users need to modify their registries.
1. Click Control Panel | System Properties | Environment Variables.
2. Under System Variables, select Path and click EDIT.
3. Add your Ruby directory to the end of the Variable Value list and
click OK.
4. Under System Variables, select PATHEXT and click EDIT.
5. Add .RB and .RBW to the Variable Value list and click OK.
Installing Applications and Libraries from RAA
If you program in Ruby for any length of time, you will need to know about the
Ruby Application Archive (RAA), which is at www.ruby-lang.org/en/raa.html
(see Figure 1.4). As fun as it is to write everything from scratch, save yourself
some time by using libraries and applications written by other Ruby developers.
The RAA contains a comprehensive list of links to Ruby applications in various
stages of development. After you develop and find a place to host your application, you can add your Ruby application to the RAA by submitting your entry at
www.ruby-lang.org/en/raa-entry.rhtml.
1. The RAA gives easy access to a wealth of applications and libraries.
Many applications install painlessly, and attached README files provide
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 9
Booting Ruby • Chapter 1
detailed instructions. For this example, we’re going to use RubyUnit,
which is a testing framework. If you use Extreme Programming,
RubyUnit provides similar functionality to JUnit or SUnit (For more
information on Extreme Programming, visit www.xprogramming.com).
Download RubyUnit from the RAA in the Library section under devel.
2. Extract the file to your hard drive
tar –xvzf rubyunit-x.x.x.tar.gz
3. Install the application, in this case, the following:
cd rubyunit-x.x.x
ruby install.rb
Other Ruby packages may use a Ruby configuration script to grab parameters before installing.The extconf.rb installation procedure is fairly straightforward.
After untarring your package, do the following:
ruby extconf.rb
make
make install
Figure 1.4 The Ruby Application Archive
www.syngress.com
9
183RubyC01.qxd
10
1/4/02
3:50 PM
Page 10
Chapter 1 • Booting Ruby
Developing & Deploying…
Getting Help
The Ruby community quickly responds to questions from both the uninitiated and advanced. If you pore through this text and the README file
associated with the library or module you’re using, and still encounter
problems, Ruby users from around the world will answer your questions
quickly.
First, perform a quick search through newsgroups to see if your
question has already been asked and answered. www.ruby-talk.org
contains a complete archive of posts to the English-based
comp.lang.ruby and Ruby’s mailing-list. Google also provides an easyto-use archive of the Ruby newsgroup (although it contains about
5,000 fewer of the early messages) at http://groups.google.com/
groups?hl=en&group=comp.lang.ruby. Polite questions draw a
response within hours, if not minutes. As an alternative, the #ruby-lang
channel on DALnet provides immediate satisfaction. You receive nearimmediate responses to your questions. However, an order of magnitude fewer users exist at any one time in IRC than those that chat
through the newsgroups/mailing-list.
IDE and Editor Support in Ruby
Your choice of editor has a direct effect on productivity, as there are strengths and
weaknesses to every editor.While some developers stick with Windows’ Notepad
for its speed and simplicity, it doesn’t support syntax highlighting, macros, and a
host of other modern editor features. Invest time early to find a powerful editor
that you like, get familiar with it, and learn to take advantage of the shortcuts.
Build macros to save yourself time.This advice remains true regardless of what
language you use for development.
Editor support for Ruby depends on the capabilities of the editor. At a minimum, your editor should support Ruby syntax highlighting, a way for your
editor to help you differentiate between keywords in your program and increase
its readability. Some editors, such as Emacs, allow “shells” to run Ruby, or Ruby
applications on code within your editor.
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 11
Booting Ruby • Chapter 1
Emacs
Configurability often comes at the cost of simplicity. Such is the case with
Emacs, an editor with a steep learning curve, but great opportunities to extend,
customize, and optimize to your development style.
Grab the latest version at ftp.gnu.org/gnu/emacs, or the Windows version at
ftp.gnu.org/gnu/windows/emacs/latest.With a little elbow grease, you can set up
Emacs for Ruby support:
1. Drop the elisp files (inf-ruby.el ruby-mode.el) into the emacs\lisp directory of your choice. For this example, I drop them into d:\emacs\lisp.
2. Add the code in Figure 1.5 to your .emacs file (located in your home
directory).
Figure 1.5 Emacs Code to Add Ruby Support
(autoload 'ruby-mode "ruby-mode"
"Mode for editing ruby source files")
(setq auto-mode-alist
(append '(("\\.rb$" . ruby-mode)) auto-mode-alist))
(setq interpreter-mode-alist (append '(("ruby" . ruby-mode))
interpreter-mode-alist))
(autoload 'run-ruby "inf-ruby"
"Run an inferior Ruby process")
(autoload 'inf-ruby-keys "inf-ruby"
"Set local key defs for inf-ruby in ruby-mode")
(add-hook 'ruby-mode-hook
'(lambda ()
(inf-ruby-keys)
))
If you enjoy tweaking Emacs, other Ruby developers have listed extensions
that they have written at www.rubygarden.org/ruby?EmacsExtensions.The page
is in Wiki format, so if you tweak Emacs, you can add your own extensions to
the list.
www.syngress.com
11
183RubyC01.qxd
12
1/4/02
3:50 PM
Page 12
Chapter 1 • Booting Ruby
VIM
VIM (Vi IMproved) is straightforward and loads quickly, and its little brother, vi,
is available on almost all Unix machines. If you’re a Windows user, or you just
haven’t grown up on vi, you may not appreciate VIM’s edit and command mode
structures.
Download VIM at www.vim.org.VIM 5.7 and above support Ruby syntax
highlighting.
Other Editors
For those budding Ruby enthusiasts who want more “Windows-like” editors,
there are a number of alternatives. If you’ve grown up on Notepad, you may
want to try TextPad. For a commercial editor,Visual SlickEdit is another powerful
alternative that receives rave reviews in the press.
Other editors that support Ruby include NEdit, JEdit, CodeWright, Kate,
and JED.There is a list of Ruby editors with extensions at the RAA. Perform a
find on Editor, and the various Ruby extensions for editors will be listed.
TextPad
A low priced and powerful Notepad replacement for Windows,TextPad loads
quickly and has a simple and straightforward interface.TextPad is shareware; there
is a 30-day trial available at www.textpad.com, and you can purchase a single-user
license online for $16.50.
You add Ruby support through the Ruby syntax file at
www.textpad.com/add-ons/ntsyn.html.
Visual SlickEdit
If you prefer commercial packages,Visual SlickEdit (www.slickedit.com) wins
high marks and comes with excellent documentation and, of course, commercial
support.The primary disadvantage to using SlickEdit is its high price tag ($295
US), especially when compared to the free Emacs and VIM.
To add Ruby Syntax highlighting, use the code found at
www.rubygarden.com/ruby?VisualSlickEditExtensions.
RubyWin
RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.
The Ruby binary installation, by Andy Hunt, supplies a version of RubyWin.You
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 13
Booting Ruby • Chapter 1
can also grab the latest version at the RAA in the Aplication section under IDE.
This application provides syntax highlighting, buffer evaluation, the Interactive
Ruby (discussed later), multiple window displays, line counts, and more. As
RubyWin comes fully configured to take advantage of Ruby tools, it’s a pretty
decent place to start.
Ruby Development Environment (RDE)
Another Windows IDE is the Ruby Development Environment (RDE), by
Sakazuki (see Figure 1.6). Features include file tabs, syntax highlighting, debugger
support, and more.You can get RDE at the RAA in the Application section
under IDE.
Figure 1.6 The RDE IDE
Additional Tools a Rubyist Must Have
While the RAA contains every known Ruby tool available, there are a couple
with which you should get familiar immediately: Ri, IRb, and debug.rb.
www.syngress.com
13
183RubyC01.qxd
14
1/4/02
3:50 PM
Page 14
Chapter 1 • Booting Ruby
Ruby Interactive (Ri)
The Ruby Interactive reference (or Ri) gives quick access to definitions, and
method names. Download Ri at www.pragmaticprogrammer.com/ruby/
downloads/ri.html.This proves invaluable when looking at other people’s source
code, when you need to view certain libraries, or when you are writing your
own application and you can’t remember a method name or usage.
Adding a macro that allows use of Ri from within your text editor provides
an additional level of convenience. For VIM, add the following code (Figure 1.7)
to your .vimrc:
Figure 1.7 .vimrc File Modifications
function Ri()
let b:x = system("ri '" . input("ri: ") . "' > /tmp/ri_output")
sp /tmp/ri_output
endfunction
map :call Ri()
Pressing F2 lets you input a class name, method, etc. and shows Ri’s output in
a new window.
For information on a class or method, just call ri with it as argument:
ri Array
This results in the following output:
-----------------------------------------------------------------------class: Array
-----------------------------------------------------------------------Arrays are ordered, integer-indexed collections of any object.
Array indexing starts at 0, as in C or Java. A negative index is
assumed relative to the end of the array—-that is, an index of -1
indicates the last element of the array, -2 is the next to last
element in the array, and so on.
-----------------------------------------------------------------------&, *, +, —, <<, <=>, ==, ===, [], [], []=, assoc, at, clear,
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 15
Booting Ruby • Chapter 1
collect, collect!, compact, compact!, concat, delete, delete_at,
delete_if, each, each_index, empty?, eql?, fill, first, flatten,
flatten!, include?, index, indexes, indices, join, last, length,
map!, new, nitems, pack, pop, push, rassoc, reject!, replace,
reverse, reverse!, reverse_each, rindex, shift, size, slice,
slice!, sort, sort!, to_a, to_ary, to_s, uniq, uniq!, unshift, |
------------------------------------------------------------------------
If you see a method that about which you need more information, you can
enter its class followed by a # and the method name, as done below:
ri "Array#collect"
This results in the following:
---------------------------------------------------------- Array#collect
arr.collect {| obj | block } -> anArray
-----------------------------------------------------------------------Returns a new array by invoking block once for every element,
passing each element as a parameter to block. The result of block
is used as the given element in the new array. See also
Array#collect!.
a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }
a
#=> ["a!", "b!", "c!", "d!"]
#=> ["a", "b", "c", "d"]
To add Emacs support, follow the directions within Ri’s /contrib/csteele or
/contrib./dblack/emacs directory.
GtkRi (Figure 1.8) is a graphical version of Ri, available at
http://bocks.dhs.org/~pizman/myri. GtkRi offers extra browsing functionality,
such as hyperlinks, tree view, and navigation buttons.This application (for Unix
systems running X) requires Ruby/Gtk, Ri, and Gtk.
Interactive Ruby (IRb)
Interactive Ruby (IRb) provides a shell for experimentation (see Figure 1.9).
Within the IRb shell, you can immediately view expression results, line by line.
Grab the latest version at www.ruby-lang.org/en/raa-list.rhtml?name=irb++interactive+ruby or use the version that comes by default with Ruby.
www.syngress.com
15
183RubyC01.qxd
16
1/4/02
3:50 PM
Page 16
Chapter 1 • Booting Ruby
Figure 1.8 GtkRi
Figure 1.9 An Interactive Ruby Session
irb 0.6.1(99/09/16)
irb(main):001:0> 1+1
2
irb(main):002:0> def hello
irb(main):003:1>
out = "Hello World"
irb(main):004:1>
puts out
irb(main):005:1> end
nil
irb(main):006:0> hello
Hello World
nil
irb(main):007:0>
The latest versions of IRb include tab completion, a feature that allows you
to save even more time.The following:
irb(main):001:0> al
completes the word as:
alias
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 17
Booting Ruby • Chapter 1
Even better, pressing the Tab key in the following situation:
irb(main):001:0> a = "aString"
irb(main):002:0> a.u
outputs all applicable methods for the object referred by variable a:
a.unpack
a.untaint
a.upcase
a.upcase!
a.upto
To activate the tab completion module, start IRb with:
irb –r irb/completion
Debugging Ruby Applications with debug.rb
Ruby comes with a debugger included.To debug a Ruby program, simply start it
with the –r debug option:
ruby –r debug applicationToDebug.rb
Suppose we have two files: test.rb (Figure 1.10) and pi.rb (Figure 1.11) that
we want to debug (not really debug, because there are no errors in them, but we
want to have a look at how they work).
Figure 1.10 File test.rb
require "pi"
arr = []
pi { |d|
arr << d
break if arr.size > 10
}
Figure 1.11 File pi.rb
def pi
k, a, b, a1, b1 = 2, 4, 1, 12, 4
loop do
# Next approximation
Continued
www.syngress.com
17
183RubyC01.qxd
18
1/4/02
3:50 PM
Page 18
Chapter 1 • Booting Ruby
Figure 1.11 Continued
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d = a / b
d1 = a1 / b1
while d == d1
yield d
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
end
end
end
Let’s start by invoking the debugger:
ruby –r debug test.rb
Debug.rb
Emacs support available.
test.rb:1:require "pi"
At first, we display the debugger’s help by typing h (or help) followed by a
carriage return.This gives us the following output:
(rdb:1) h
Debugger help v.-0.002b
Commands
b[reak] [file|method:]
set breakpoint to some position
wat[ch]
set watchpoint to some expression
cat[ch]
set catchpoint to an exception
b[reak]
list breakpoints
cat[ch]
show catchpoint
del[ele][ nnn]
delete some or all breakpoints
disp[lay]
add expression into display expression list
www.syngress.com
183RubyC01.qxd
1/4/02
3:50 PM
Page 19
Booting Ruby • Chapter 1
undisp[lay][ nnn]
delete one particular or all display
expressions
c[ont]
run until program ends or hit breakpoint
s[tep][ nnn]
step (into methods) one line or till
line nnn
n[ext][ nnn]
go over one line or till line nnn
w[here]
display frames
f[rame]
alias for where
l[ist][ (-|nn-mm)]
list program, - lists backwards
nn-mm lists given lines
up[ nn]
move to higher frame
down[ nn]
move to lower frame
fin[ish]
return to outer frame
tr[ace] (on|off)
set trace mode of current thread
tr[ace] (on|off) all
set trace mode of all threads
q[uit]
exit from debugger
v[ar] g[lobal]
show global variables
v[ar] l[ocal]
show local variables
v[ar] i[nstance]
Source Exif Data:
File Type : PDF
File Type Extension : pdf
MIME Type : application/pdf
PDF Version : 1.3
Linearized : Yes
Create Date : 2002:01:15 11:33:29
Producer : Acrobat Distiller 4.0 for Macintosh
Creator : QuarkXPressª 4.1: LaserWriter 8 8.6.5
Author :
Title : 183_ruby_FC
Modify Date : 2002:01:28 17:20:41-05:00
Page Count : 721
Page Mode : UseOutlines
Page Layout : OneColumn
EXIF Metadata provided by EXIF.tools