1 YEAR UPGRADE
BUYER PROTECTION PLAN
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
RUBY
Developer’s
Guide
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 ser-
vice 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.
is an interactive treasure trove of useful infor-
mation 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 i
183_Ruby_FM.qxd 1/7/02 4:04 PM Page ii
1 YEAR UPGRADE
BUYER PROTECTION PLAN
Robert Feldt
Lyle Johnson
Michael Neumann
Technical Editor
Ruby
Developer’s Guide
183_Ruby_FM.qxd 1/7/02 4:04 PM Page iii
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 SERIAL NUMBER
001 UJG4TFR2T5
002 AKJ7T4MAS4
003 VMERF3854N
004 SGD34BK9HN
005 85DFMU6N7H
006 NFG438GEM4
007 BAQ2HTR46T
008 CV5TR56KMR
009 83N5M4BT6Y
010 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 iv
v
Acknowledgments
v
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.
183_Ruby_FM.qxd 1/7/02 4:04 PM Page v
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 partici-
pate in such a great development.
vi
183_Ruby_FM.qxd 1/7/02 4:04 PM Page vi
vii
Contributors
Jason Wong is the Chief Executive Officer of ionami design, a Web
development and design firm headquartered in Berkeley, CA. His respon-
sibilities include developing and maintaining client relationships, project
management, application development and support, and operations man-
agement. 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 bioinfor-
matics 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
183_Ruby_FM.qxd 1/7/02 4:04 PM Page vii
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 back-
ground. 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 equa-
tions, advanced calculus, financial mathematics, and model theory. In addi-
tion, Stephen has over 10 years of software development expertise in such
areas as fixed income derivatives, interest rate modeling, artificial intelli-
gence, and telecommunications. He has authored computer graphics
engines, computer chess games, option pricing engines, cellular propaga-
tion models, and workflow management systems. He is currently con-
sulting on the IRROS project and on J2EE-related technologies in the
Washington, DC area.
183_Ruby_FM.qxd 1/7/02 4:04 PM Page viii
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 develop-
ment 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.
183_Ruby_FM.qxd 1/7/02 4:04 PM Page ix
183_Ruby_FM.qxd 1/7/02 4:04 PM Page x
Contents
xi
Foreword xxiii
Chapter 1
Booting Ruby 1
Introduction 2
An Overview of Ruby 2
Installing Ruby and its Tools 3
Installing Ruby on Unix 5
Installing Ruby from Source Code 5
Installing from Packages 7
Installing Ruby on a Windows System 7
Installing Applications and Libraries
from RAA 8
IDE and Editor Support in Ruby 10
Emacs 11
VIM 12
Other Editors 12
RubyWin 12
Ruby Development Environment (RDE) 13
Additional Tools a Rubyist Must Have 13
Ruby Interactive (Ri) 14
Interactive Ruby (IRb) 15
Debugging Ruby Applications
with debug.rb 17
A Short Syntax Style Guide 22
Using Comments 22
Naming 23
Iterators 24
Indentation, Spacing, Parentheses 24
■
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.
183RubyToC.qxd 1/7/02 4:31 PM Page xi
xii Contents
Dangerous Ruby 25
Local Variables versus Methods 25
More Whitespace Issues 25
Block Local Variables 26
Comparing Ruby 26
Java 26
Perl 32
Language Constructs 32
Object-Oriented Programming 33
Access Control 34
Arrays and Hashes 35
Hashes 36
Iterators 36
Convincing Management to Use Ruby 37
Summary 39
Solutions Fast Track 39
Frequently Asked Questions 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 xii
Contents xiii
Using the Glade GUI Builder 87
Using the FOX Toolkit 90
Obtaining FOX and FXRuby 90
FXRuby Basics 91
Targets and Messages 93
Working with FOX’s Layout Managers 95
Fox Sample Application 99
Using the SWin/VRuby Extensions 111
Obtaining SWin and VRuby 112
VRuby Library Basics 112
Layout Managers 116
Event Handling 118
VRuby Sample Application 120
Other GUI Toolkits 127
Choosing a GUI Toolkit 128
Summary 129
Solutions Fast Track 130
Frequently Asked Questions 132
Chapter 3
Accessing Databases with Ruby 135
Introduction 136
Accessing Databases with Ruby/DBI 136
Obtaining and Installing Ruby/DBI 140
Programming with Ruby/DBI 141
Understanding Ruby/DBI Architecture
and Terminology 143
Connecting to Databases 144
Using Driver URLs and
Datasource Names 146
Preparing and Executing SQL Statements 148
Fetching the Result 156
Performing Transactions 162
Handling Errors 164
Tracing the Execution of
DBI Applications 166
Accessing Metadata 169
Master the Grid Layout
Manager
183RubyToC.qxd 1/7/02 4:31 PM Page xiii
xiv Contents
Using Driver-specific Functions
and Attributes 171
Accessing Databases Remotely Using
DBD::Proxy 174
Copying Table Data between
Different Databases 175
Getting Binary Objects Out of a Database 176
Transforming SQL-query Results to XML 179
Accessing Databases with Ruby/ODBC 190
Accessing LDAP Directories with Ruby/LDAP 195
Using Ruby/LDAP 195
Adding an LDAP Entry 196
Modifying an LDAP Entry 196
Deleting an LDAP Entry 197
Modifying the Distinguished Name 197
Performing a Search 197
Handling Errors 199
Utilizing Other Storage Solutions 199
Reading and Writing Comma-Separated
Value Files 199
Using Berkeley DBM-file Databases 200
Using the Berkeley DB Interface BDB 201
Storing Ruby Objects in a Relational
Database 205
Summary 208
Solutions Fast Track 208
Frequently Asked Questions 209
Chapter 4
XML and Ruby 211
Introduction 212
Why XML? 212
Making XML Manageable 214
Validation though DTD 214
Validating With XML-Schemas 216
XPath 218
XML Parser Architectures and APIs 218
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.
183RubyToC.qxd 1/7/02 4:31 PM Page xiv
Contents xv
Parsing and Creating XML in Ruby 221
Shared Code for Examples 228
Defining and Implementing Classes
Host and Port 229
Defining and Implementing the
Report Class 230
Using XMLParser 234
Installing XMLParser on Unix 234
Using NQXML 240
Installing NQXML 241
Using REXML 251
Using XSLT in Ruby 254
Ruby-Sablotron 254
XSLT4R 254
Summary 256
Solutions Fast Track 257
Frequently Asked Questions 258
Chapter 5
Web Services and Distributed Ruby 261
Introduction 262
Using XML-RPC for Ruby 262
Obtaining and Installing xmlrpc4r 263
Configuring xmlrpc4r 263
Writing XML-RPC Clients 264
Using the MultiCall Extension 268
Introspecting XML-RPC Servers 268
Writing XML-RPC Servers 270
Project: A File Upload Service 274
XML-RPC Datatypes 276
User-defined Datatypes 278
Dumping and Loading XML-RPC Messages 278
Communicating with Python’s xmlrpclib 279
Securing XML-RPC Services 280
Client-side Support 280
Server-side Support 281
Performance Comparisons 281
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-to-
understand English.
183RubyToC.qxd 1/7/02 4:31 PM Page xv
xvi Contents
Using SOAP for Ruby 284
Obtaining and Installing SOAP4R 286
Writing SOAP4R Client and Server
Applications 286
Choosing an XML Parser 288
Writing SOAP4R Clients 289
Writing SOAP4R Services 298
SOAP Datatypes and Type-Conversion 303
Creating Multi-dimensional or
Typed SOAP Arrays 306
Creating User-defined Datatypes 306
Changing the Default Type-Mapping 308
Using SOAP as Marshalling Format 310
Project: A SOAP Authentification Server 313
Using Distributed Ruby 321
A Name Server for DRb 324
Using DRb to Speed Up CGI Scripts 325
Using Rinda and Distributed TupleSpaces 328
Load-Balancing 331
Security Considerations 333
Summary 336
Solutions Fast Track 336
Frequently Asked Questions 337
Chapter 6
WWW and Networking with Ruby 339
Introduction 340
Connecting to the Web with Ruby 340
Low-Level Functions:The Socket Class 340
High-Level Functions:The Net Class 341
POP/SMTP 341
HTTP 342
FTP 342
Telnet 344
Writing a Server in Ruby 345
Models of Server Architectures 345
Basic Web Servers Using Ruby 347
Monitoring TCP/IP Based
Services
We can monitor Web
services, or any TCP/IP-
based 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]).
183RubyToC.qxd 1/7/02 4:31 PM Page xvi
Contents xvii
Using Ruby on the Web 355
Generating HTML with Ruby 356
Ruby HTML Code Generation 356
Ruby CGI HTML Generation 357
Scripting With Ruby Using eruby and ERb 358
Templating With Ruby 359
Using the HTML/Template Extension 359
Using Ruby-tmpl 361
Putting It All Together 361
Implementing an Online Shopping Application 361
Designing the Data Model 362
The Database Access Layer 366
Initializing the Database 369
Developing the Web Interface 372
Improving the Online Shop 379
Using mod_ruby and eruby 383
Installing and Configuring mod_ruby 384
Using mod_ruby and eruby in the
Online Shop Example 386
Dynamically Generating XML with eruby 395
Displaying RSS News Channels 396
Installing and Configuring IOWA 400
Using IOWA for the Online Shop Example 404
Implementing a TreeView Component 410
Summary 420
Solutions Fast Track 420
Frequently Asked Questions 422
Chapter 7
Miscellaneous Libraries and Tools 423
Introduction 424
Graphics Programming in Ruby 424
Using OpenGL in Ruby 425
Defining the Goal and the Strategy 425
Starting with a Sample Program 425
Creating Multiple Curves 434
Generating Diagrams with GD::Graph 441
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.
183RubyToC.qxd 1/7/02 4:31 PM Page xvii
N
OTE
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.
xviii Contents
Mathematical Programming in Ruby 442
Using the NArray Library 442
Using the BigFloat Library 447
Using the Polynomial Library 448
Using the Algebra Extension 454
Working with Polynomials 454
Working with Matrices 455
Exploring C/S Data-Structure Tools 460
Using the BinaryTree Extension 460
Using the BitVector Extension 464
Using Random Numbers, Genetic Algorithms,
and Neural Nets 467
Working with a Random-Number Generator 467
Genetic Programming in Ruby 468
Neural Nets 475
Working with Ruby and Windows 482
Using ActiveScript in Ruby 482
Using WinOLE in Ruby 484
Using OOP-Related Tools 488
Using the EachDelegator Library 488
Using the Preserved, Forwardable, and
Finalize Modules 489
Using Text-Processing, Date, and Calendar Tools 493
Using the Soundex Extension 493
Using the Date2 and Date3 Extensions 494
Using the Calendar Extension 496
Using Language Bindings 498
Using JRuby 498
Ruby Calling Java 499
Java Calling Ruby 503
Using the Ruby/Python Extension 507
Summary 511
Solutions Fast Track 511
Frequently Asked Questions 513
183RubyToC.qxd 1/7/02 4:31 PM Page xviii
Contents 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
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.
183RubyToC.qxd 1/7/02 4:31 PM Page xix
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.
xx Contents
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 613
Introduction 614
Writing C/C++ Extensions 615
Working with Datatype Conversions 618
Working with Objects 618
Working with Numbers 619
183RubyToC.qxd 1/7/02 4:31 PM Page xx
Contents xxi
Working with Strings 620
Working with Arrays 623
Working with Hashes 627
Working with C/C++ Data Wrappers 627
Implementing Methods 632
An Example: K-D Trees 635
Ruby Implementation of the K-D Tree 636
Compiling the C Implementation
of the K-D Tree 656
Comparing the Results 657
Using SWIG 658
A Simple SWIG Example in C 658
Using SWIG With C++ 661
Choosing SWIG 666
Embedding Ruby 666
Configuring Extensions with Mkmf 671
Summary 674
Solutions Fast Track 674
Frequently Asked Questions 676
Index 677
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.
183RubyToC.qxd 1/7/02 4:31 PM Page xxi
183RubyToC.qxd 1/7/02 4:31 PM Page xxii
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 pro-
gramming 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 documenta-
tion 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 pro-
ductive programmer with Ruby—and that you have fun reading it and performing
the examples.
xxiii
Foreword
183Ruby_fore.qxd 1/7/02 4:32 PM Page xxiii
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 lan-
guages. 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 equiva-
lent 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 xxiv