Simple Ruby Examples

PreviousTable of ContentsNext
Getting and Installing RubyCommenting Ruby Code

Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99

Not only is Ruby a flexible scripting language in terms of its syntax, it is also highly flexible in the ways in which scripts can be executed. In this chapter we will begin by looking at some simple Ruby examples, and then look at the variety of different ways Ruby code can be executed.

The Most Basic Ruby Example

Programming guides tend to follow the tradition of using "Hello World" as the first example of using a programming language. Typically such a program does nothing but output the string "Hello World" to the console window. Ruby Essentials is no exception to this rule, though we will modify it slightly to display "Hello Ruby!". Without further delay, let's get started:

On Linux or UNIX derived operating systems:

print "Hello Ruby!\n"

On Windows:

print "Hello Ruby!"

As you can see, all we need to do to output some text is enter a single line of Ruby code. You may recall if you have read the previous chapters that one of the strengths of Ruby is that it is fast and intuitive to learn. Clearly it would be hard to make printing a line of text any easier than a print statement followed by the text to be displayed (together with a newline character '\n' on Linux and UNIX).

As an example, let's compare this to the equivalent code in Java:


public class Hello {

        public static void main ( String[] args)
                System.out.println ("Hello Ruby!\n");

Hopefully, you are now beginning to see why Ruby is so popular. Programming languages such as Java require a significant amount of structure before even the simplest of tasks can be performed. Before we go any further we need to learn how to execute our first Ruby example. This can be done in a number of ways, each of which will be covered in the following sections of this chapter.

Executing Ruby from the Command Line

Ruby allows lines of code to be executed as command line options to the ruby tool. This is achieved by using the '-e' command line flag. To execute our example 'Hello Ruby!' code, therefore, we could enter the following command:

ruby -e 'print "Hello Ruby!\n"'
Hello Ruby!

The '-e' flag only allows a single line of code to be executed, but that does not mean that multiple '-e' flags cannot be placed on a single command line to execute multiple lines:

ruby -e 'print "Hello Ruby!\n"' -e 'print "Goodbye Ruby!\n"'
Hello Ruby!
Goodbye Ruby!

Interactive Ruby Execution

In the What is Ruby? we discussed the fact that Ruby is an interpreted language. This essentially means that Ruby source code is compiled and executed at run time, rather than pre-compiled as is the case with languages such as C or C++. One of the advantages of being an interpreted language is that we can write Ruby code directly into the interpreter and have it executed interactively and in real-time. This is a great way to learn Ruby and to try out different code structures.

Interactive Ruby code is entered using the irb tool. If you are running Windows and installed Ruby using the one click installer, you already have irb installed. If you are running on Linux, there is a good chance irb is not yet installed. Verify the installation as follows:

irb -v
irb 0.9(02/07/03)

If you do not get the appropriate version information displayed, you will need to install irb. On Red Hat or Fedora Linux this can be achieved as follows:

yum install irb

On Debian, Ubuntu or other Debian derived Linux distributions use the apt-get tool:

sudo apt-get install irb

Once irb is installed, launch it as follows:

$ irb

Now, we can begin to execute Ruby code:

irb(main):001:0> puts 'Hello Ruby'
Hello Ruby
=> nil

We could also perform a calculation or two:

irb(main):002:0> 3 + 4
=> 7
irb(main):003:0> 8 * 7
=> 56
irb(main):004:0> 10 % 2
=> 0

As you can see, anything we type at the irb prompt gets executed as soon as we press the Enter key. Ruby truly is an interactive, interpreted language.

Executing Ruby from a File

Clearly the command line approach to execution is of limited use once you get beyond a few lines of Ruby script. A much more common approach is to place the Ruby script in a file, and then pass that file to the Ruby interpreter to run. To try this, create a file called hello.rb using your favorite editor and enter the following lines into it:

print "Hello Ruby!\n"
print "Goodbye Ruby!\n"

To execute this script, simply refer to it on the command line when launching ruby:

ruby hello.rb
Hello Ruby!
Goodbye Ruby!

Creating a Self Contained Ruby Executable on Linux or UNIX

Placing Ruby code into a file is obviously much easier and practical than using multiple -e command line options. Suppose, however, that we want to go one step further and be able to execute a Ruby based program simply by typing the name of the file containing the code, rather than prefixing it with the ruby command.

This can be achieved on Linux or UNIX by placing a special line at the top of the script file informing the environment responsible for executing the program (such as a Linux command shell) where to look for the Ruby interpreter. This special line consists of a '#', a '!' and the path to the ruby executable and is known affectionately as the shebang.

Firstly, you need to know where ruby is located on your system. Assuming it is already in your PATH environment variable you can use the which command to find it:

which ruby

Given that ruby is in /usr/bin on the above system we can modify our sample application accordingly:

print "Hello Ruby!\n"
print "Goodbye Ruby!\n"

We can now try running our hello.rb script:

-bash: ./hello.rb: Permission denied

Clearly if you got the above output, there is a problem. This is simply a matter of the script not having execute permission. This can easily be rectified by using the chmod command to add execute permission to our script:

chmod 755 hello.rb

If we now try again we should get better results:

Hello Ruby!
Goodbye Ruby!

Associating Ruby Files on Windows

The Shebang approach outlined in the preceding chapter does not work on Windows. The #! line will just be UNIX gibberish to a Windows system. The best way to configure a Windows system to detect that a file with a .rb file extension is to be launched with Ruby is to use Windows file type associations.

If you have used Windows extensively you will be familiar with the concept that it is possible to double click, for example, on a .doc file and have that file automatically loaded into Microsoft Word. This works because the system has been configured to associate .doc files with Word. Associating .rb files with Ruby is essentially the same thing.

First, it is important to note that if you installed Ruby on Windows using the One-Click Installer then .rb files will already have been associated with Ruby, so there is no need to perform the steps in this section. Simply type hello.rb at the command prompt and our example will run.

If you built Ruby yourself from the source code, or installed using a mechanism other than the One-Click Installer, you will need to associate .rb files with Ruby. The steps to achieve this are as follows:

Begin by checking whether the association is already configured:

C:\MyRuby>assoc .rb
File association not found for extension .rb

Assuming that the association is not already configured, take the following steps to complete the configuration:

C:\MyRuby>assoc .rb=rbFile

Check to see if the file type rbfile already exists:

C:\MyRuby>ftype rbfile
File type 'rbfile' not found or no open command associated with it.

Assuming it does not already exist (be sure to substitute the path to your Ruby installation in the following command):

C:\MyRuby>ftype rbfile="D:\Ruby\bin\ruby.exe" "%1" %*

Verify the setting:

C:\MyRuby>ftype rbfile
rbfile="D:\ruby\bin\ruby.exe" "%1" %*

Add .rb to the PATHEXT environment variable as follows:

C:\MyRuby>set PATHEXT=.rb;%PATHEXT%

Once the above settings are configured simply run the program by typing the filename at the command prompt (the .rb filename extension is not required):

C:\MyRuby> hello
Hello Ruby

The above steps can be placed in your Autoexec.bat file if you would like this association made every time you reboot your system.

Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99

PreviousTable of ContentsNext
Getting and Installing RubyCommenting Ruby Code