Ruby Tutorials for Programmers of Other Languages: Everything Is an Object, Remember That

From what you’ve seen on the last two tutorials I bet you are thinking that Ruby is starting to look a lot like PHP, but the truth is Ruby is one of the most object oriented programming languages and you are about to see why.

Note: Throughout this tutorial I will use the words "methods" and "functions" interchangeably. I say this because programmers from different languages might not have heard one or the other, but they are the same thing.

Let’s say you wanted to get a string’s length, in a not so OOP language what you would do is call a static method.

This is what you would do in PHP for example.

echo strlen($stringVariable);

But in Ruby, since everything is an object, the string length is a method that is part of the string. So this is what you would do to get a string’s length.

puts stringVariable.length

Relating Ruby to Other Languages:

If you come from JAVA or C++ you are already familiar with the syntax for calling functions or instance variables, but if you’ve only used PHP all you need to know is that instead of using “->”, you use a dot “.” .

This is what the previous would look like if both languages, Ruby and PHP, used the same operator symbol.

puts stringVariable->length

In the Ruby code above I called the length method upon a variable but, since everything in Ruby is an object, I could call the method directly upon any string. I could have done this for example.

Calling a function directly upon a string

How do I know what functions are available to an object?

You are probably now wondering how to know what methods you may call on objects, I have two answers for this question.

The first is to call yet another function on the object whose methods you wish to see, this method is fittingly called “methods” and you can use it like this.

Showing methods belonging to a string

The other solution would be to get a text editor that will show the available functions as you type.

Eclipse IDE

Remember, every in Ruby in an object.