Everything is an Object in Ruby

The first thing you should learn about Ruby first into 5 words. It’s all encompassing and it’s philosophy is underpinned by this phrase:

Literally. Everything. Is. An. Object.

I think examples are worth a thousand words so let’s just get to it.

So in PHP, we have classes and objects too. But we also have these very basic data scructures called scalar types. A scalar type are your primitive data types - things like strings and integers. You know, the simple stuff.

Well, the biggest difference compared to Ruby right off the bat is that even those simple data structures are objects.

So, in our new fancy console make a string - just like you would in PHP:

    $ irb
    2.4.3 :001 > 'Hello World'
     => "Hello World"

Cool, nothing fancy so far. Things are same.

But like I said, everything in Ruby has an object.

So let’s say we want to get the count of characters in our simple string. In PHP we use functions that accept certain scalar types because scalar types aren’t objects:

    $ php -a
    php > echo strlen('Hello World');

But in Ruby, there’s a rich interface on a String object, and we’d get the length of the string like so:

    $ irb
    2.4.3 :001 > 'Hello World'.length
     => 11

The other powerful aspect of Ruby is the consistency in the language. For example, this length method works just fine on Arrays (technically Array objects, you get the idea):

    $ irb
    2.4.3 :001 > ['Hello', 'World'].length
     => 2

But in contrast, in PHP we have a separate function for counting the contents in an array:

    $ php -a
    php > count(['Hello', 'World']);
     => 2

Pretty cool right? The methods are intuitive and easy to remember. You’ll find yourself looking at the Ruby documentation less and less.

Just to drive the point home, you don’t even have to use a function like get_class()in order to get the class of our String object. Everything in Ruby has a .class method that will give you the class of our object:

    $ irb
    2.4.3 :001 > 'Hello World'.class
    => String

Crazy right? Here’s PHP’s equivalent:

    $ php -a
    php > $object = new stdClass();
    php > echo get_class($object);
     => stdClass

The one word methods are just simple.

Object Instantiation

Man back in the hayday of my PHP days, if only I had a dollar for everytime I typed $.

Sorry, terrible joke, but I couldn’t help myself.

So of course you know in PHP we have to declare our variables like so:

    $cliche = 'Hello World';

2 rules in PHP:

  1. All variables must begin with $
  2. All statements need to end with ;

Well in Ruby, that’s not necessary:

    cliche = 'Hello World'

Done that’s it. Section over. Fin.