O'Reilly logo

The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Try Ruby

We hope our tour of Ruby’s key features has piqued your interest and you are eager to try Ruby out. To do that, you’ll need a Ruby interpreter, and you’ll also want to know how to use three tools—irb, ri, and gem—that are bundled with the interpreter. This section explains how to get and use them.

The Ruby Interpreter

The official web site for Ruby is http://www.ruby-lang.org. If Ruby is not already installed on your computer, you can follow the download link on the ruby-lang.org home page for instructions on downloading and installing the standard C-based reference implementation of Ruby.

Once you have Ruby installed, you can invoke the Ruby interpreter with the ruby command:

% ruby -e 'puts "hello world!"'
hello world!

The -e command-line option causes the interpreter to execute a single specified line of Ruby code. More commonly, you’d place your Ruby program in a file and tell the interpreter to invoke it:

% ruby hello.rb
hello world!

Displaying Output

In order to try out Ruby features, you need a way to display output so that your test programs can print their results. The puts function—used in the “hello world” code earlier—is one way to do this. Loosely speaking, puts prints a string of text to the console and appends a newline (unless the string already ends with one). If passed an object that is not a string, puts calls the to_s method of that object and prints the string returned by that method. print does more or less the same thing, but it does not append a newline. For example, type the following two-line program in a text editor and save it in a file named count.rb:

9.downto(1) {|n| print n }   # No newline between numbers
puts " blastoff!"            # End with a newline

Now run the program with your Ruby interpreter:

% ruby count.rb

It should produce the following output:

987654321 blastoff!

You may find the function p to be a useful alternative to puts. Not only is it shorter to type, but it converts objects to strings with the inspect method, which sometimes returns more programmer-friendly representations than to_s does. When printing an array, for example, p outputs it using array literal notation, whereas puts simply prints each element of the array on a line by itself.

Interactive Ruby with irb

irb (short for “interactive Ruby”) is a Ruby shell. Type any Ruby expression at its prompt and it will evaluate it and display its value for you. This is often the easiest way to try out the language features you read about in this book. Here is an example irb session, with annotations:

$ irb --simple-prompt       # Start irb from the terminal
>> 2**3                     # Try exponentiation
=> 8                        # This is the result
>> "Ruby! " * 3             # Try string repetition
=> "Ruby! Ruby! Ruby! "     # The result
>> 1.upto(3){|x| puts x }   # Try an iterator
1                           # Three lines of output 
2                           # Because we called puts 3 times
=> 1                        # The return value of 1.upto(3)
>> quit                     # Exit irb
$                           # Back to the terminal prompt

This example session shows you all you need to know about irb to make productive use of it while exploring Ruby. It does have a number of other important features, however, including subshells (type “irb” at the prompt to start a subshell) and configurability.

Viewing Ruby Documentation with ri

Another critical Ruby tool is the ri[1] documentation viewer. Invoke ri on the command line followed by the name of a Ruby class, module, or method, and ri will display documentation for you. You may specify a method name without a qualifying class or module name, but this will just show you a list of all methods by that name (unless the method is unique). Normally, you can separate a class or module name from a method name with a period. If a class defines a class method and an instance method by the same name, you must instead use :: to refer to the class method or # to refer to the instance method. Here are some example invocations of ri:

ri Array
ri Array.sort
ri Hash#each
ri Math::sqrt

This documentation displayed by ri is extracted from specially formatted comments in Ruby source code. See Documentation comments for details.

Ruby Package Management with gem

Ruby’s package management system is known as RubyGems, and packages or modules distributed using RubyGems are called “gems.” RubyGems makes it easy to install Ruby software and can automatically manage complex dependencies between packages.

The frontend script for RubyGems is gem, and it’s distributed with Ruby 1.9 just as irb and ri are. In Ruby 1.8, you must install it separately—see http://rubygems.org. Once the gem program is installed, you might use it like this:

# gem install rails
Successfully installed activesupport-1.4.4
Successfully installed activerecord-1.15.5
Successfully installed actionpack-1.13.5
Successfully installed actionmailer-1.3.5
Successfully installed actionwebservice-1.2.5
Successfully installed rails-1.2.5
6 gems installed
Installing ri documentation for activesupport-1.4.4...
Installing ri documentation for activerecord-1.15.5...

As you can see, the gem install command installs the most recent version of the gem you request and also installs any gems that the requested gem requires. gem has other useful subcommands as well. Some examples:

gem list               # List installed gems
gem enviroment         # Display RubyGems configuration information
gem update rails       # Update a named gem
gem update             # Update all installed gems
gem update --system    # Update RubyGems itself
gem uninstall rails    # Remove an installed gem

In Ruby 1.8, the gems you install cannot be automatically loaded by Ruby’s require method. (See Loading and Requiring Modules for more about loading modules of Ruby code with the require method.) If you’re writing a program that will be using modules installed as gems, you must first require the rubygems module. Some Ruby 1.8 distributions are preconfigured with the RubyGems library, but you may need to download and install this manually. Loading this rubygems module alters the require method itself so that it searches the set of installed gems before it searches the standard library. You can also automatically enable RubyGems support by running Ruby with the -rubygems command-line option. And if you add -rubygems to the RUBYOPT environment variable, then the RubyGems library will be loaded on every invocation of Ruby.

The rubygems module is part of the standard library in Ruby 1.9, but it is no longer required to load gems. Ruby 1.9 knows how to find installed gems on its own, and you do not have to put require 'rubygems' in your programs that use gems.

When you load a gem with require (in either 1.8 or 1.9), it loads the most recent installed version of the gem you specify. If you have more specific version requirements, you can use the gem method before calling require. This finds a version of the gem matching the version constraints you specify and “activates” it, so that a subsequent require will load that version:

require 'rubygems'               # Not necessary in Ruby 1.9
gem 'RedCloth', '> 2.0', '< 4.0' # Activate RedCloth version 2.x or 3.x
require 'RedCloth'               # And now load it

You’ll find more about require and gems in The Load Path. Complete coverage of RubyGems, the gem program, and the rubygems module are beyond the scope of this book. The gem command is self-documenting—start by running gem help. For details on the gem method, try ri gem. And for complete details, see the documentation at http://rubygems.org.

More Ruby Tutorials

This chapter began with a tutorial introduction to the Ruby language. You can try out the code snippets of that tutorial using irb. If you want more tutorials before diving into the language more formally, there are two good ones available by following links on the http://www.ruby-lang.org home page. One irb-based tutorial is called “Ruby in Twenty Minutes.”[*] Another tutorial, called “Try Ruby!”, is interesting because it works in your web browser and does not require you to have Ruby or irb installed on your system.[]

Ruby Resources

The Ruby web site (http://www.ruby-lang.org) is the place to find links to other Ruby resources, such as online documentation, libraries, mailing lists, blogs, IRC channels, user groups, and conferences. Try the “Documentation,” “Libraries,” and “Community” links on the home page.

[1] Opinions differ as to what “ri” stands for. It has been called “Ruby Index,” “Ruby Information,” and “Ruby Interactive.”

[*] At the time of this writing, the direct URL for this tutorial is http://www.ruby-lang.org/en/documentation/quickstart/.

[] If you can’t find the “Try Ruby!” link on the Ruby home page, try this URL: http://tryruby.hobix.com.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required