Introduction to Ruby

Everything you need to know to start programming in Ruby.
Classes and Methods

Finally, we can put this all together in defining a class and some methods. We can create a class in irb, or anywhere else in Ruby, simply by saying:

class Simple
end

Sure enough, we've managed to create a class in only two lines. Is this enough to create an object of type Simple? Let's see:

foo = Simple.new
foo.class

It would seem so; our variable foo claims that it is of class Simple. We didn't specify what object Simple inherits from, so it automatically inherits from Object, the ultimate Ruby superclass. Ruby supports only single inheritance, which is stated in the class definition as:


class SimpleArray < Array
end

We already have defined two classes, which is nice, but we haven't defined any methods specific to those classes. Ruby allows us to open up a class at any time, adding or replacing methods in a class. We define a method with the def statement, indicating whether the method takes any parameters, for example:

class Simple
    def id_squared
        return self.object_id * self.object_id
    end
end

The method we have defined is quite simple, and it does something that I don't expect we would ever want to do—namely, it takes the object's unique ID (available via the inherited method object_id) and returns its doubled value (which will likely be an instance of Bignum).

If we type the above definition into irb, something amazing happens: our foo variable of class Simple now responds to the method Simple#id_squared! Yes, Ruby allows us to modify methods on the fly and to open up existing classes. We could, for example, modify the built-in Array or String classes, replacing the built-in methods with some of our own.

Finally, we might want to store some state in our object. This is done via instance variables. In Ruby, instance variables are preceded with the @ character, which might be a bit confusing if you are coming from the Perl world:

class Simple
    def initialize
        @simple_data = [ ]
    end
end

The special initialize method is invoked whenever we create a new instance of Simple. So if we once again define foo to be an instance of Simple:

foo = Simple.new

we can see that foo now has an instance variable defined, by invoking:

foo.instance_variables

The above returns an array:

["@simple_data"]

How can we assign to @simple_data? And how can we retrieve its value? One way is to define a number of methods: one for writing this instance variable and one for retrieving its value. But a shorthand way would be to use the attr_reader and attr_writer methods:

class Simple
    attr_reader :simple_data
    attr_writer :simple_data
end

The above code tells Ruby we have an instance variable named @simple_data, and that we would like to have methods created that will allow us to read and set its value. You can see here how symbols allow us to refer to an instance variable by something that is not a string, but not the literal variable either. With this in place, we can do things like:

foo = Simple.new
foo.simple_data = 'abc'
foo.simple_data = [1, 2, 3]
print foo.simple_data.join(', ')

Conclusion

Ruby has become extremely popular in the last year or two, in no small part because of the growth of Ruby on Rails among Web developers. Even without Rails though, Ruby deserves much of the attention it has received. The fact that all data is stored in objects, the compactness and elegance of the method and block structures, and the very large number of objects included in the standard library all make for an impressive language.

This article didn't have space to go into some additional features that will be of interest to many Ruby programmers, such as modules, class variables, input/output with files, networking, XML parsing, the RubyGems library available on the Internet and built-in support for regular expressions. Ruby is a rich language, but it is fairly consistent and easy to learn—assuming you already have some background with object-oriented programming, which I think is the greatest hurdle to understanding Ruby.

Ruby still has a number of issues to resolve, including its relatively slow speed and a lack of Unicode support, but these are being addressed for future versions, and the community is one of the strongest that I've seen.

I have been using Ruby more and more during the last year and have grown to be quite impressed with the language. I suggest that you give Ruby a whirl as well. Even if you don't make it your primary programming language, it will get you thinking in new ways, and it might make programming in other languages more enjoyable too.

Resources for this article: /article/9017.

Reuven M. Lerner, a longtime Web/database consultant, is currently a PhD student in Learning Sciences at Northwestern University in Evanston, Illinois. He and his wife recently celebrated the birth of their son Amotz David.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Inspired by You

noman13bd's picture

Hi, i read this article and install and do some programming with RoR. Here is some of example what i do
Ruby On Rails installation on Windows
Ruby on Rails installation in Ubuntu
autocompleter example in RoR
live Validation for RoR

Ismail Muhammad Noman
share-facts.blogspot.com

I'm only just starting to

Anonymous's picture

I'm only just starting to learn Ruby, but this seems wrong:

"We also can view a subset of the original array by passing two indexes separated by a comma, indicating the first and last index that we want:

an_array[0,1]"

Shouldn't it be "indicating the first index and the LENGTH OF THE SUBSTRING that we want"?

Nice and fast intro (plus two typos)

Praxis's picture

Greetings.
I enjoyed this fast intro to Ruby, which quickly points out the basics with nice and clear examples for anyone with some programming experience to easily go hands-on.

I did notice these two typos:

1. When you mention string conversion methods, it is written "You can convert a string to an integer or float using the to_i and to_s methods", but I believe you meant "to_i and to_f"

2. When you give the "id_squared" method example, you mention in the explaining paragraph that it "returns its doubled value", where it should be the "squared value"

Regardless of this, I did enjoy reading this intro.

Congratulations.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix