序
本书是Ruby程序设计语言的参考手册。用Ruby,在写好程序的基础上,你还能提高生产效率,并享受编程过程。
这虽然是一种大胆的观点,但是我相信您会在读完本书之后会同意他们的观点。这是我们的亲身经历。
作为注重实效的程序员,我们尝试了很多种语言,我们用这些工具简化我们的工作,工具确实也能让我们更好的工作。可是此前我们用过的语言一直让我们失望。
我们的工作目的就是解决问题,而不是做编译器,所以我们喜欢动态语言,它适应我们,没有独断性(arbitrary),有严格的规则。我们能用代码顺畅的沟通,能用代码正确有效的表达需求。而且,我们写的代码越少,出错的机会也越少(这样也会减少我们的手腕和手指的工作量)。
我们要求尽可能的提高生产效率,所以我们希望写完代码之后马上能运行起来;我们必须从开发时间中留出时间用于调试。他也能帮助我们在编写时提炼代码;如果你必须花费两个小时写一个循环,那你可能也要用punch cards和成批编辑提交你的工作。(We want to be as productive as possible, so we want our code to run the first time; time spent in the debugger is time stolen from the development clock. It also helps if we can try out code as we edit it; if you have to wait for a 2-hour make cycle, you may as well be using punch cards and submitting your work for batch compilation. )
我们需要一个具有很高抽象层的语言,语言的抽象层越高,我们把需求转化为代码所需的时间越少。
当我们发现了Ruby,我们认识到我们找到了我们在一直寻找的东西。和我们用过的其他语言相比,ruby显得【stays out of your way】,你可以集中精力处理手边的事情,而不必去过多的陷在编译器和语言问题中。ruby正是如此让你能成为一个更好的程序员:你只需专心地为用户解决问题,而不是和编译器纠缠。
Ruby的闪光点
采用从真正的面向对象语言,比如Smalltalk,摒弃除去那些未成熟新奇的语法,创造更多的有用的,忠实于文档的代码。这样Ruby也加入到这些适应性强且又实用的工具(比如:Python and Perl)之中。你或许要终身使用Ruby作为你的工具了。(Take a true object-oriented language, such as Smalltalk. Drop the unfamiliar syntax and move to more conventional, file-based source code. Now add in a good measure of the flexibility and convenience of languages such asPython and Perl . You end up with Ruby. )
OO爱好者有很多原因喜欢Ruby:纯面向对象(任何东西都是对象),元类,闭包,迭代,无处不在的集合。Smalltalk用户会感到很熟悉(c++和java用户可能会嫉妒了)。
同时,perl和python的拥护者也有他们很多喜欢perl或者python的特点:完全的正则表达式的支持,与底层操作系统的紧密结合,便利的捷径,以及动态调用。
Ruby很容易去学习,每天的任务是简单的编写代码,完成之后,这些代码很容易维护和完善。不过毕竟,很多困难的事情最初或许并不被认为很困难。但是Ruby遵循的是Principle of Least Surprise原理,即:事情会按你的预想发展,并且几乎没有特例或者例外。当然,就是这点让你在编程时感觉到不同。( is easy to learn. Everyday tasks are simple to code, and once you've done them, they are easy to maintain and grow. Apparently difficult things often turn out not to have been difficult after all. Ruby follows thePrinciple of Least Surprise---things work the way you would expect them to, with very few special cases or exceptions. And that reallydoesmake a difference when you're programming. )
我们称 Ruby为透明语言。这就是说, Ruby不会让你写下的解决方案因众多的语法而模糊不清,
We call Ruby a
transparentlanguage. By that we mean that Ruby doesn't obscure the solutions you write behind lots of syntax and the need to churn out reams of support code just to get simple things done. With Ruby you write programs close to the problem domain. Rather than constantly mapping your ideas and designs down to the pedestrian level of most languages, with Ruby you'll find you can express them directly and express them elegantly. This means you code faster. It also means your programs stay readable and maintainable.
使用Ruby,我们可能会经常为它的特点感到惊奇,没有那么多得语法错误,没有类型错误,更少的bug。这很有用,它会让我们更少出错,没有在每行结尾机械式的加入分号,省得类型定义的麻烦(特别是分散在多个文件中的时候)。没有不需要的语句会让编译器报错。
那么,为什么要学习ruby呢?因为我们认为它能帮助我们更好的编程,它将帮助你把主要注意力集中在实质的东西上,而不必过分分心。总之,它将使你生活变得容易。
Ruby是一种什么样的语言?
In the old days, the distinction between languages was simple: they were either compiled, like C or Fortran, or interpreted, like BASIC. Compiled languages gave you speed and low-level access; interpreted languages were higher-level but slower.
Times change, and things aren't that simple anymore. Some language designers have taken to calling their creations ``scripting languages.'' By this, we guess they mean that their languages are interpreted and can be used to replace batch files and shell scripts, orchestrating the behavior of other programs and the underlying operating system. Perl, TCL, and Python have all been called scripting languages.
What exactly
isa scripting language? Frankly we don't know if it's a distinction worth making. In Ruby, you can access all the underlying operating system features. You can do the same stuff in Ruby that you can in Perl or Python, and you can do it more cleanly. But Ruby is fundamentally different. It is a true programming language, too, with strong theoretical roots and an elegant, lightweight syntax. You
couldhack together a mess of ``scripts'' with Ruby, but you probably won't. Instead, you'll be more inclined to
engineera solution, to produce a program that is easy to understand, simple to maintain, and a piece of cake to extend and reuse in the future.
Although we have used Ruby for scripting jobs, most of the time we use it as a general-purpose programming language. We've used it to write GUI applications and middle-tier server processes, and we're using it to format large parts of this book. Others have used it for managing server machines and databases. Ruby is serving Web pages, interfacing to databases and generating dynamic content. People are writing artificial intelligence and machine learning programs in Ruby, and at least one person is using it to investigate natural evolution. Ruby's finding a home as a vehicle for exploratory mathematics. And people all over the world are using it as a way of gluing together all their different applications. It truly is a great language for producing solutions in a wide variety of problem domains.
Ruby适合我吗?
Ruby is not the universal panacea for programmers' problems. There will always be times when you'll need a particular language: the environment may dictate it, you may have special libraries you need, performance concerns, or simply an issue with training. We haven't given up languages such as Java and C++ entirely (although there are times when we wish we could).
However, Ruby is probably more applicable than you might think. It is easy to extend, both from within the language and by linking in third-party libraries. It is portable across a number of platforms. It's relatively lightweight and consumes only modest system resources. And it's easy to learn; we've known people who've put Ruby code into production systems within a day of picking up drafts of this book. We've used Ruby to implement parts of an X11 window manager, a task that's normally considered severe C coding. Ruby excelled, and helped us write code in hours that would otherwise have taken days.
Once you get comfortable with Ruby, we think you'll keep coming back to it as your language of choice.
为什么我们要写这本书?
So we'd just finished writing
The Pragmatic Programmer,our families had just started talking to us again, and suddenly we felt the need to write another book. Why? We guess it comes down to a kind of missionary zeal.
Ruby was created by Yukihiro Matsumoto (Matz) in Japan. Since 1995, its popularity in Japan has grown at an astounding rate; there are rumors that Ruby is more popular than Python in Japan. But to date, much of the detailed Ruby documentation is in Japanese. It probably isn't a programming language you'd just stumble across.
We wanted to spread the word, to have more people outside Japan using Ruby and enjoying the benefits, so we decided to document Ruby in English. And what started out as a small project just sort of grew....
Ruby 版本
This book documents Version 1.6 of Ruby, which was released in September 2000.
Ruby version numbering follows the same scheme used for many other open source projects. Releases with even subversion numbers (1.0, 1.2, 1.4, and so on) are stable, public releases. These are the releases that are prepackaged and made available on the various Ruby Web sites.
Development versions of the software have odd subversion numbers, such as 1.1 and 1.3. These you'll have to download and build for yourself, as described in the box on page xxvii.
安装 Ruby
You can get Ruby from ftp://ftp.netlab.co.jp/pub/lang/ruby, or from the mirror sites listed on page 526 in Appendix C. There you will find the latest stable release, as well as various development releases.
You'll always find source code releases of Ruby; you may also find prebuilt binaries for Windows or other operating systems (like the binary distribution of Ruby for Windows at http://www.pragmaticprogrammer.com/ruby/downloads/ruby-install.html).
Sidebar: 最新版的 Ruby |
For those who just have to be on the very latest, hot-off-the-press anduntestedcutting edge (as we were while writing this book), you can get development versions straight from the developers' working repository.The Ruby developers use CVS (Concurrent Version System, freely available from http://www.cvshome.com) as their revision control system. You can check files out as an anonymous user from their archive by executing the following CVS commands:% cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs
login
(Logging in to anonymous@cvs.netlab.co.jp)
CVS password: guest
% cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs
checkout ruby The complete source code tree, just as the developers last left it, will now be copied to a ``ruby'' subdirectory on your machine, updating your local source tree from a repository on the other side of the world. Isn't it a great time to be alive? |
Building Ruby
In the Ruby distribution you'll find a file named
README
, which explains the installation procedure in detail. To summarize, you build Ruby on POSIX-based systems using the same four commands you use for most other open source applications:
./configure
,
make
,
make test
, and
make install
. You can build Ruby under other environments (including Windows) by using a POSIX emulation environment such as
cygwin
[See http://sourceware.cygnus.com/cygwin for details.]or by using native compilers---see ``
ntsetup.bat
'' in the distribution's
win32
subdirectory as a starting point.
运行 Ruby
Now that Ruby is installed, you'd probably like to run some programs. Unlike compiled environments, there are two ways to run Ruby---interactively and as a program.
交互式 Ruby
The easiest way to run Ruby interactively is simply to type ``ruby'' at the shell prompt.
% ruby puts "Hello, world!" ^D Hello, world! |
Here we typed in the single
puts
expression and an end of file character (which is control-D on our system). This process works, but it's sort of painful if you make a typo, and you can't really see what's going on as you type.
In the
sample
directory in the Ruby distribution you'll find a script named ``
eval.rb
''. It goes one step better by showing us the value of each expression as it is entered:
% cd sample % ruby eval.rb ruby> a = "Hello, world!" "Hello, world!" ruby> puts a Hello, world! nil ruby> ^D % |
Here we can see the output from
puts
, and then the return value from
puts
(which is
nil
).
That's all fine and well, except that multiline expressions do not work, and you can't edit the line you're on, or go back and use previous lines (as you might with command history in a shell).
For the next step up from
eval.rb
, we have
irb
---Interactive Ruby.
irb
is a Ruby Shell, complete with command-line history, line editing capabilities, and job control. It is quite configurable and has many options, so much so that it has its own appendix beginning on page 517. We recommend that you get familiar with
irb
so you can try some of our examples interactively.
Ruby 程序
Finally, you can run a Ruby program from a file as you would any other shell script, Perl program, or Python program. You can simply run Ruby giving the script name as an argument:
Or you can use the Unix ``shebang'' notation as the first line of the program file.
[If your system supports it, you can avoid hard-coding the path to Ruby in theshebangline by using#!/usr/bin/env ruby
, which will search your path forruby
and then execute it.]
#!/usr/local/bin/ruby -wputs "Hello, World!" |
If you make this source file executable (using, for instance,
chmod +x myprog.rb
), Unix lets you run the file as a program:
% ./myprog.rb Hello, World! |
You can do something similar under Microsoft Windows using file associations.
资源
Visit the Ruby Web sites, http://www.rubycentral.com and http://www.ruby-lang.org, to see what's new, and chat with other Ruby users on the newsgroup or mailing lists (see Appendix C).
And we'd certainly appreciate hearing from you. Comments, suggestions, errors in the text, and problems in the examples are all welcome. E-mail us at:
mailto:rubybook@pragmaticprogrammer.com
If you tell us about errors in the book, we'll add them to the errata list at:
http://www.pragmaticprogrammer.com/ruby/errata/errata.html
Finally, http://www.pragmaticprogrammer.com/ruby also contains the source code for almost all the book's examples, organized by page.
致谢
A book is a massive undertaking, one that we would never be able to complete without help from our all our friends, old and new. We're proud to count among our old friends the team at Addison-Wesley: Mike Hendrickson, John Fuller, the ever-helpful Julie Steele, and the wonderful Julie DiNicola. Thank you all.
Our reviewers were fantastic. We put them up against some incredibly tight deadlines and they came through for us. Reviewing a book full of technical detail isn't easy, so we're especially grateful to George Coe, Bob Davison, Jeff Deifik, Hal Fulton, Tadayoshi Funaba, Clemens Hintze, Kazuhiro Hiwada, Kikutani Makoto, Mike Linksvayer, Aleksi Niemel? Lew Perin, Jared Richardson, Armin Roehrl, Conrad Schneiker, Patrick Schoenbach, and Eric Vought. Thanks also go to the two Julies at Addison-Wesley for coordinating this truly international effort.
Several people helped us with specific areas of this book. Tadayoshi Funaba exchanged countless e-mails with us until we finally understood the
Date
module. Guy Decoux and Clemens Hintze patiently answered our questions about writing Ruby extensions, and Masaki Suketa helped us understand the
WinOLE
module.
Although much of the original Ruby documentation is in Japanese, there is a growing body of English translations, mostly undertaken by Japanese developers whose skills with English never cease to amaze us. Although there are too many individual contributions to this effort to name each author, we would like to single out Goto Kentaro, who has produced a large volume of high-quality documentation and placed it online.
Finally, we have to thank Yukihiro ``Matz'' Matsumoto, the creator of Ruby. We've lost count of the number of questions we've asked of him, and the number of patient and detailed answers he's sent back. As well as creating a truly wonderful language, Matz has fostered a wonderfully supportive and open culture in which that language can prosper.
Thank you all. Domo arigato gozaimasu.
Dave Thomasand
Andy Hunt
T
HEP
RAGMATICP
ROGRAMMERS
http://www.pragmaticprogrammer.com
符号约定
Throughout this book, we use the following typographic notations.
Literal code examples are shown using a typewriter-like font:
class SampleCode def run #... end end |
Within the text,
Fred#doIt
is a reference to an instance method (
doIt
) of class
Fred
, while
Fred.new
[In some other Ruby documentation, you may see class methods written asFred::new
. This is perfectly valid Ruby syntax; we just happen to feel thatFred.new
is less distracting to read.]is a class method, and
Fred::EOF
is a class constant.
The book contains many snippets of Ruby code. Where possible, we've tried to show what happens when they run. In simple cases, we show the value of expressions on the same line as the expression. For example:
a = 1 |
b = 2 |
a + b |
?/td> |
3 |
At times, we're also interested in the values of assignment statements, in which case we'll show them.
a = 1 |
?/td> |
1 |
b = 2 |
?/td> |
2 |
a + b |
?/td> |
3 |
If the program produces more complex output, we show it below the program code:
3.times { puts "Hello!" } |
produces:
In some of the library documentation, we wanted to show where spaces appear in the output. You'll see these spaces as ``
'' characters.
Command-line invocations are shown with literal text in a Roman font, and parameters you supply in an
italicfont. Optional elements are shown in large square brackets.
ruby[flags]*[progname][arguments]+ |
Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/)).Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.