Let's write a function to compute factorials. The
mathematical definition of
n factorial is:
n! = 1 (when n==0) = n * (n-1)! (otherwise)
In ruby, this can be written as:
if n == 0
n * fact(n-1)
You may notice the repeated occurrence of
has been called "Algol-like" because of this. (Actually, the
syntax of ruby more closely mimics that of a langage named
Eiffel.) You may also notice the lack of a
statement. It is unneeded because a ruby function returns the
last thing that was evaluated in it. Use of a
statement here is permissible but unnecessary.
Let's try out our factorial function. Adding one line of code gives us a working program:
# Save this as fact.rb
if n == 0
n * fact(n-1)
ARGV is an array which contains the command line
to_i converts a character string to an
% ruby fact.rb 5
Does it work with an argument of 40? It would make your calculator overflow...
It does work. Indeed, ruby can deal with any integer which is allowed by your machine's memory. So 400! can be calculated:
We cannot check the correctness at a glance, but it must be right. :-)
When you invoke ruby with no arguments, it reads commands from standard input and executes them after the end of input:
puts "hello world"
puts "good-bye world"
The ^D above means control-D, a conventional way to signal end-of-input in a Unix context. In DOS/Windows, try pressing F6 or ^Z instead.
Ruby also comes with a program called
eval.rb that allows you to
enter ruby code from the keyboard in an interactive loop, showing you
the results as you go. It will be used extensively through the rest
of this guide.
If you have an ANSI-compliant terminal (this is almost certainly true
if you are running some flavor of UNIX; under old versions of DOS you
need to have installed
ANSI.COM; Windows XP,
unfortunately, has now made this nearly impossible), you should use
eval.rb that adds visual
indenting assistance, warning reports, and color highlighting.
Otherwise, look in the
sample subdirectory of the ruby
distribution for the non-ANSI version that works on any terminal.
Here is a short
ruby> puts "Hello, world."
hello world is produced by
puts. The next
line, in this case
nil, reports on whatever was last
evaluated; ruby does not distinguish between statements and
expressions, so evaluating a piece of code basically means
the same thing as executing it. Here,
puts does not return a meaningful value. Note
that we can leave this interpreter loop by saying
^D still works too.
Throughout this guide, "
ruby>" denotes the input prompt
for our useful little