5.0 Classes

Grouping Objects

At this point, one may wonder if all objects are the same. Are the groupings we've already covered - numbers, strings, arrays - supported by the Ruby language?

Ruby does in fact allow one to define groups of objects, or, to use object oriented jargon, classes of objects.

One may look up the class of any object by simply calling the class method on it. Let's try it out with a few of the objects we're already familiar with.

Example Code:

Output Window

As you can see, Ruby tells us what we already suspected - that 1 is a Fixnum (a special case of Integer), "" is a String and [] is an Array.

We can also turn this interrogation around. Here, we'll ask whether an object is_a? particular class.

Example Code:

Output Window

Classes are people too

An important feature of classes in Ruby is that they too adhere to the "everything is an object philosophy." This may be of interest to those already familiar with C++ and similar languages where classes are special constructs that cannot be interacted with like normal objects.

So, in Ruby, classes themselves are simply objects that belongs to the class Class. Here's a simple example that demonstrates this fact:

Example Code:

Output Window

What do classes do?

The next logical question is, of course, do classes simply act as logical groupings, or do they actually do something?

In Ruby, like other class-based object oriented languages that you may already be familiar with, classes act as the factories that build objects. An object built by a certain class is called 'an instance of that class.' Typically, calling the new method on a class results in an instance being created.

Let's build an instance of the most basic kind of object by calling the method new on the object Object.

This object - or instance, to be more precise - can't do very much. However, instances of more powerful classes like Arrays and Strings can do a whole lot more as we'll see in other lessons. You will also learn to create your own classes which you can then use to build bigger and more powerful programs.

Congratulations, guest!

% of the book completed


This lesson is Copyright © 2011-2014 by Sidu Ponnappa and Jasim A Basheer