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.
1.2.1 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!
Other Ruby Implementations
In the absence of a formal specification for the Ruby language, the Ruby interpreter
from ruby-lang.org is the reference implementation that defines the language. It is
sometimes known as MRI, or “Matz’s Ruby Implementation.” For Ruby 1.9, the original MRI interpreter was merged with YARV (“Yet Another Ruby Virtual machine”) to
produce a new reference implementation that performs internal compilation to bytecode and then executes that bytecode on a virtual machine.
The reference implementation is not the only one available, however. At the time of
this writing, there is one alternative implementation released at a 1.0 level (JRuby) and
several other implementations under development:
1.2 Try Ruby | 11
JRuby
JRuby is a Java-based implementation of Ruby, available from http://jruby.org. At
the time of this writing, the current release is JRuby 1.0, which is compatible with
Ruby 1.8. A 1.9-compatible release of JRuby may be available by the time you read
this. JRuby is open source software, developed primarily at Sun Microsystems.
IronRuby
IronRuby is Microsoft’s implementation of Ruby for their .NET framework and
DLR (Dynamic Language Runtime). The source code for IronRuby is available
under the Microsoft Permissive License. At the time of this writing, IronRuby is
not yet at a 1.0 release level. The project home page is http://www.ironruby.net.
Rubinius
Rubinius is an open source project that describes itself as “an alternative Ruby
implementation written largely in Ruby. The Rubinius virtual machine, named
shotgun, is based loosely on the Smalltalk-80 VM architecture.” At the time of this
writing, Rubinius is not at version 1.0. The home page for the Rubinius project is
http://rubini.us.
Cardinal
Cardinal is a Ruby implementation intended to run on the Parrot VM (which aims
to power Perl 6 and a number of other dynamic languages). At the time of this
writing, neither Parrot nor Cardinal have released a 1.0 version. Cardinal does not
have its own home page; it is hosted as part of the open source Parrot project at
http://www.parrotcode.org.
1.2.2 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
12 | Chapter 1: Introduction
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.
1.2.3 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
3
=> 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.
1.2.4 Viewing Ruby Documentation with ri
Another critical Ruby tool is the ri
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
- Opinions differ as to what “ri” stands for. It has been called “Ruby Index,” “Ruby Information,” and “Ruby Interactive.” 1.2 Try Ruby | 13 This documentation displayed by ri is extracted from specially formatted comments in Ruby source code. See §2.1.1.2 for details. 1.2.5 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... ...etc... 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 §7.6 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. 14 | Chapter 1: Introduction 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 §7.6.1. 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://ruby gems.org. 1.2.6 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.† 1.2.7 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.
Top comments (0)