Ruby For Programmers – Part 2: Everything is an Object

This concept should come up sooner rather than later in Ruby texts:

Everything is in Object.

Unlike some languages where certain things have certain special types (Javascript and Lua has different types, like number, string, and ‘object’, Java has ‘special’ types like int), everything in Ruby is an object. Objects can be different classes, but they all descend from Object. So for our integers earlier, they too are objects.

If you are unfamiliar with the concept of Object-Oriented Programming, just know this: Objects are buckets that have methods and instance variables. (And those instance variables are also Objects toooo!) So if you have an object, you can run a method on it. Methods are in dot notation in Ruby so:

The first statement shows the five plus five we know from earlier. The second shows that “5+5” is just short hand for “Take 5 and run the method named ‘+’ with the method arguments of ‘4’”.

Since everything is an object, there’s no real need to have outside libraries do things. For example, to round a Float, just call “round”, and it will round itself. It makes sense when you think about it, a Float should know how to round itself, and doesn’t need a helper to do it.

Objects themselves have base methods. So for example, you can find out what class something is by calling class:

So we see that “5” is an instance of the “Fixnum” class. (Also we can see that Fixnum itself, is an instance of Class, and Class is an instance of Class.)

If you want to know what class something is, just use is_a?:

So how can 5 be both a “Fixnum” and an “Integer”? That’s easy, Object Hierarchy. Let’s look at Fixnum’s ancestors:

So it appears that 5 has an ancestry when in comes to it’s classes, and thus inherits some classes in-between.

This is probably a bit too much for right now, but it’s important to know for later: the reason why we are calling methods on Strings and Arrays like we will in the future, is that they are Objects and they are having their methods called on like any other Object. Again, the difference is that some languages have types, so you need to call methods on types that know about the datatype. Example: strlen(string) in C/PHP vs. string.length in Ruby.

As a technical note, some Objects are more Objecty than others. Built-in classes, like Fixnum, String, Symbol, Array, Hash, Date, etc. have a much faster interpretation in the interpreter itself. So while they are all truly objects from a programming standpoint, the basic datatypes are stored and processed in an efficient manner.