Ruby Tutorial for Absolute Beginners

Get started with the Ruby programming language. In this tutorial you learn how to install Ruby, how to write simple Ruby scripts, and how to create Ruby classes and objects. Includes example code to get you up and running.

The Ruby programming language is becoming increasingly popular, thanks to its clean syntax, its object-oriented features, and its range of high-quality libraries and frameworks.

In this tutorial, you get a gentle introduction to programming in Ruby. You learn:

How Ruby works, and what it's used for

How to install Ruby on your Mac, Windows PC, or Linux PC

How to create — and run — your first Ruby script

Some of Ruby's object-oriented programming features

How to create and use classes and objects, and

How to use Interactive Ruby to explore the Ruby language.

At the end of the tutorial, you also explore some resources for taking your Ruby skills further.

Let's start with a brief introduction to Ruby, and take a look at the language's features and benefits.

Introducing Ruby

Ruby is a powerful, yet easy-to-learn object-oriented programming language with a nice clean syntax. It was invented in Japan in the mid-nineties, but has really taken off in recent years, largely thanks to the Ruby on Rails framework, which lets you easily write powerful dynamic websites and web apps in Ruby.

As well as being popular with web developers, Ruby is also used for many other purposes, including system administration tasks and writing GUI-based desktop apps for Windows, Mac OS and Linux.

Ruby is, by default, an interpreted language, much like PHP, Perl and Python. This means that you need to install a Ruby interpreter to process and run your Ruby programs and scripts.

There are also Ruby compilers available that can turn your Ruby code into stand-alone apps.

In the next section, you begin your Ruby journey by installing a Ruby interpreter on your Mac or PC.

Installing Ruby

In order to start programming in Ruby, you first need to install the Ruby interpreter on your computer. The Ruby interpreter is the program that takes your Ruby script files and runs them.

The following sections briefly cover how to install Ruby on a Mac, on a Windows PC, and on a Linux PC.

Installing on a Mac

Have a Mac? Lucky you! Ruby comes pre-installed in Mac OS X. Proceed to the next section.

Installing on a Windows PC

RubyInstaller is an app that installs a complete, self-contained Ruby environment on your PC. It's the quickest way to get Ruby up and running on a Windows machine.

To install Ruby on a Windows 7 PC using RubyInstaller, follow these steps:

Download RubyInstaller
Visit the RubyInstaller downloads page and download the latest installer; at the time of writing, this is rubyinstaller-2.0.0-p0195.exe.

Run the installer
Double-click the .exe file to run the installer. In the Security Warning dialog that appears, click Run. In the Select Setup Language dialog that appears, choose your language and click OK. Follow the installer wizard. Make sure you select the "Add Ruby executables to your PATH" and "Associate .rb and .rbw files with this Ruby installation" options, since it will make it easier for you to run your Ruby scripts.

Installing on a Linux PC

Installing Ruby on Linux partly depends on what distro you use. For Debian-based systems (including Ubuntu), you can just run the following command, replacing "1.9.1" with the currently-available Ruby version:

sudo apt-get install ruby1.9.1

If you prefer a GUI approach, you can instead use a package manager such as Ubuntu Software Center to install the Ruby package.

If you start getting seriously into Ruby development on Linux, you might prefer to install RVM (Ruby Version Manager) and use it to install and update Ruby, rather than using the distro's package manager. RVM is generally better at keeping your Ruby system and libraries up to date.

Display a prompt.
The first line of code displays the message "Hello, what's your name?" on the screen. To do this, it calls a method named puts, passing the string argument "Hello, what's your name?" to the method. If you're not familiar with object-oriented programming, a method is a piece of code attached to a class, object, or module. When you call a method (by typing its name in your script), Ruby runs the code inside the method. The puts, or "put string", method happens to be attached to a built-in Ruby module called Kernel, and its job is to output its string argument to the terminal window.

You explore classes, objects and methods in more detail later in this tutorial.

Get the user's name.
Now that we've prompted the user to type their name, we need to read the text that they enter on the keyboard. We do this by calling the gets method in line 2. This method is the opposite of puts; whereas puts outputs a string of text, gets reads in a string of text typed in by the user, and returns it. We then take this string value, which is actually an object (more on that in a moment), and call the object's chomp method; this simple method merely removes the newline from the end of the string (created when you press Return on your keyboard to enter the string). We then store the resulting string in a new variable called name.

Display a greeting.
Finally, line 3 displays a greeting message to the user. The message consists of the string "Hi there, ", followed by the user's name (stored in the name variable), followed by an exclamation mark (!). Again, we use the puts method to display the greeting. We also use the concatenation operator, +, to join the three strings together to produce the greeting string.

Running the script

Try this script out! Open your terminal window and use the cd command to change to the folder holding your greeting.rb file. Type the following:

ruby greeting.rb

Then press Return. You should see the following message:

Hello, what's your name?

Type your name, then press the Return (Enter) key on your keyboard. You'll see a message similar to the following:

Hi there, Matt!

Congratulations — you've just created and run your first Ruby script!

In Ruby, almost everything is an object

Ruby is, at heart, an object-oriented language, so to write Ruby code effectively you need to understand OOP (object-oriented programming) concepts such as classes, objects, properties and methods. If you're not familiar with these concepts, have a quick read through Object-Oriented PHP for Absolute Beginners. It includes PHP code, but the OOP concepts also apply to Ruby.

While many languages, such as PHP, have object-oriented features, with Ruby the concept of object-oriented programming goes much deeper. In Ruby, almost everything in the language is an object, with methods that you can run, and instance variables (sometimes known as properties) that you can access via getter and setter methods. This includes:

Objects that you create from your own classes

Objects created from built-in Ruby classes and Ruby modules

Basic data types, such as numbers, strings, arrays, hashes, and even classes themselves

Even literal values, such as the number 3, are objects! This means you can, quite legitimately, call methods on the number 3, like this:

As in many other OOP languages, the dot (.) operator calls methods. object.method means: "Call method on object".

The hash (#) symbol signifies a comment. Everything from the hash to the end of the line is ignored by the Ruby interpreter.

If you run this Ruby script, you get the following output:

Fixnum
false
1.5

Let's look at how the script works:

Line 1 calls the class method of the 3 object. This method returns the class of the object as a string, which is then displayed with puts. You can see that 3's class is Fixnum, a built-in class that stores and handles integer numbers.

Line 2 calls the even? method of the 3 object. (Yes, method names in Ruby can include punctuation such as ? and !.) even? returns a Boolean value: true if the number is even; false if it's not. The code then displays this Boolean value (false in this case) using puts.

Even false is an object in Ruby! It belongs to a class named FalseClass.

Line 3 calls the fdiv method of the 3 object. fdiv takes a floating-point number as an argument — 2 in this case — and divides the object's value (3) by the argument to produce the result, 1.5, which puts then displays. (1.5 is an object of the Float class.)

As you can see, the fact that almost everything in Ruby is an object makes the language both powerful and intuitive. Being able to call methods on almost anything gives you a lot of flexibility, and helps you write succinct, readable code.

Creating a Member class

Now that you understand the basic concepts of classes and objects in Ruby, have a go at creating a class yourself. Save the following file as member.rb:

This very simple script creates a class called Member that you might use to handle members who login to your site or app. Let's explore each part of this script:

The Member class definition
The first and last lines of code, class Member and end, tell Ruby that we want to create a new class called Member. All the code between these two lines defines how the Member class behaves.

The constructor
Lines 3 to 6 form the class's constructor. A constructor is a method that is called automatically whenever a new object of the class is created. In Ruby, the constructor method is always called initialize.

To create a method, you use this syntax:

def methodName
# method code here
end

Or, if you want your method to take arguments:

def methodName(argumentList)
# method code here
end

Our constructor method takes a single argument: username. It then defines two variables: @username, which it sets to the value of the username argument, and @loggedIn, which it sets to false.

These two variables are instance variables, signified by the fact that they begin with an at symbol (@). An instance variable (sometimes called a property) is a variable that is associated with each object created from the class. So each Member object that we create has its own @username and @loggedIn instance variables. @username stores the member's username; @loggedIn tracks whether the member is logged in or not.

Our constructor, then, lets us create new, logged-out Member objects with each member's username set to an initial value.

The username accessor method
Lines 8-10 create a method called username. This method takes no arguments. Its single line of code merely references the @username instance variable. In Ruby, the last expression evaluated within a method is sent back as the return value to the code that called the method. The line:

So the username method simply returns the value of the @username instance variable to the code that called the method. This is known as an accessor method (more specifically, a reader method) because its sole purpose is to give outside code access to the @username instance variable.

In OOP it's considered bad practice to allow outside code to read and alter instance variables directly; you should (nearly) always add accessor methods to the class, and use those instead.

The login and logout methods
The login method on lines 12-14, like the username method, takes no arguments. It simply sets the value of the @loggedIn instance variable to true, thereby marking the member as "logged in". Similarly, the logout method on lines 16-18 sets @loggedIn to false.

The loggedIn? method
The last method defined in the Member class is loggedIn?, created on lines 20-22. It returns true if the member is logged in, or false if they're logged out.
As mentioned earlier, method names can contain punctuation symbols, and it is a common Ruby programming convention to use method names ending in a question mark (?) for methods that return a Boolean value.

Since loggedin? simply returns the value of the @loggedIn instance variable, it is in effect an accessor method for @loggedIn.

Creating and using a Member object

Now that we've built our Member class, let's try using it to create a Member object. Add the following lines of code to the end of your member.rb file:

Create a new Member object
The first line of new code - line 26 — creates a new Member object and stores it in a member variable. To do this, it calls the new method of the Member class. This method is built into all Ruby classes; it creates a new object of the class, then calls the class's initialize method (if present). We pass a string ("Fred") to Member's initialize method, which then sets its @username instance variable to "Fred" and its @loggedIn instance variable to false.

Display the member's status
Line 27 calls our new Member object's username accessor method, which returns the value of the @username instance variable ("Fred"). It also calls the loggedin? method to determine if the @loggedIn instance variable is true; if so, it displays the message "Fred is logged in". In this case, loggedIn? returns false, so it displays "Fred is logged out".

The if..then..else..end construct operates much like it does in other languages. If the expression is true, the code block between then and else is run. Otherwise, the code block between else and end is run.

Notice that, in Ruby, you can simply write an expression ("in" or "out") in a code block, whereas in most languages you would need to write a statement (such as x = "in" or print "out"). Ruby evaluates the whole if..then..else..end construct as an expression; in this case it evaluates to "out", which we then append to the "Fred is logged " string using the + operator.

Log the member in
On line 28 the code logs the member in by calling the object's login method, which sets its @loggedIn instance variable to true. Line 29 then displays the member's status again, as described in Step 2 above. This time the message displayed is: "Fred is logged in".

Log the member out
Line 30 logs the member out again by calling the object's logout method, setting its @loggedIn instance variable to false. Finally, line 31 displays the member's status, as described in Step 2. Now the message displayed is: "Fred is logged out".

Interactive Ruby: Playing with Ruby code

Now that you have a basic understanding of some key Ruby features, a good way to explore the language further is to play around with Interactive Ruby. This is a useful program that comes with your Ruby installation; it lets you type in lines of Ruby code and immediately see the results.

To run Interactive Ruby, open a terminal window and type:

irb

Then press Return. You'll see a prompt (>>) appear. Type in a line of Ruby code, and press Return to see what your code evaluates to. Here are some examples (the typed-in code is in bold):