Archive for Everything Is An Object

Everything Is An Object in Ruby

In Ruby, everything is an object.

That’s right, including those “primitive types” as understood by other languages.

Even classes are an instance of a class. Funky.

But what does mean?

For starters, it means everything has an interface for method invocation.

Results:

Hello World
Hello World
Hello World
Hello World
Hello World

Note: In Ruby you can make numbers easier to read by separating them with a delimiter (in this case the underscore).

To find out whether an object can “respond to” a certain method invocation, is as simple as:

As a Numeric (1) cannot respond to a downcase, it returns a false.

Note:

  • :downcase is a Symbol. Anything prefixed with a colon is a Symbol. A Symbol is like a quick way to represent a constant without defining it, or giving it any value. For all intensive purposes its to make it easy to identify certain things in Ruby. For example, fields, methods, keys, and many more, it is not limited to just this.
  • The String method downcase helps to downcase/lowercase the letters

Epiphany

When I started Ruby programming, I was at awe when I saw object instantiation.
In Ruby:

Compare to the traditional style, in PHP:

new is a class method of the User class, and not a statement of its own.

Behind The Scenes: The Creation of a Ruby Class

So since all classes are a class of Class, when you define a new class, like so:

Behind the scenes you are actually creating an instantiation from the Class class:

They both accomplish the same thing.

Together With The Power of Open Classes

As everything is an object, and Ruby allows Open Classes, the core classes of Ruby can be easily extended to adapt to your needs. See my previous posts about Open Classes.

Example:

Comments