Ruby for PHP Developers

With our knowledge of PHP we can learn a lot about Ruby. Use of variables, loops, arrays, functions and classes, everything starting from PHP. In the end, there is an example to see all together where we’ll combine what we have learnt to see something really useful in action.

Brief Introduction

We could say PHP and Ruby (plus a framework) are the most used language in the Internet. There are many reasons, but the best one for our purpose is they are very similar in some points. So we are going to learn Ruby using those points as a support, and, trust me, if you know a little bit more about PHP than echo, it’s going to be pretty easy to learn the basis of Ruby.

These are the steps you need to follow to install Ruby in your operating system.

Variables

Ruby is a dynamic language, just like PHP, so we don’t need to define a variable. The difference here is the types, Ruby is a strongly typed language, so if we want to convert an integer into a string we need to call the proper function. Take a look at this couple of examples using variables in PHP and Ruby.

<?php
$number = 3;
echo "The number is " . $number;
?>

number = 3
puts "The number is " + number.to_s

These scripts have the same objective, concatenate a number to a string, and display the result. We can observe the first differences with PHP:

The echo function of PHP is “puts” in Ruby. We use puts to show the result of a function or just for debugging purposes.

There is no end of line with semicolon, so the line finishes when a new one starts.

The concatenation in Ruby is made with the plus sign, not with point.

As we have said before, in Ruby we need to convert the type integer into string to show it. (In the PHP example we just use it, and the programming language takes care of its conversion).

As you might guess, there is a function for every type conversion, so we have “to_i” to integer, “to_f” to float and “to_s” to string.

Arrays and other structured variables

The use of arrays is as simple as in PHP, basically we can do most of the things we do in PHP with the tools Ruby offers us. Let’s see the first step to use arrays, its creation and the access to them. By default the index of an array starts in 0.

In the last three lines there is an important point to be noticed. We called animals.first instead of first(animals). That’s because arrays are objects. But arrays are not the only ones, strings, numbers, hashes are also objects. As we have seen in the last example, we’ll usually call to a function with something like “x.function” instead of “function(x)”.

Conditionals, loops and functions

Conditionals

We have seen the basics of Ruby, but we need more to do something useful. Ruby has the same classic conditionals that PHP: if, else, elsif (not elseif!). All the conditionals structures finishes with “end”, and we don’t have to put parenthesis like in PHP, it’s optional in Ruby.

number = 70
if number > 90
puts 'This number is near to 100'
elsif number > 50
puts 'This number is greater than 50'
else
puts 'This number is less than 50'
end
# The output will be: 'This number is greater than 50'

Loops and functions

In PHP the loops and functions are as simple as in Ruby. In Ruby we have basically similar loops to the ones we have in PHP, but the syntax is a little bit different, let’s kill two birds with one stone and see the functions and loops in the same example, trust me, it’s going to be easy.

# Function definition
def show_elements(array)
array.each_with_index do |element,index| # Similar to foreach in PHP
puts "#{element} is in the array at #{index} position."
end
end
animals = ['dogs', 'cats', 'spiders']
# We call the function
show_elements(animals) # We can also call it with "show_elements animals"

Its output is going to be:

Let’s see the others loops. Here we have a typical while where we increment a counter, very similar to the while in PHP, right?

times = 4
now = 1
while now <= times
puts "Iteration number #{now} of #{times}"
now += 1
end

There is one kind of loop we have in Ruby and not in PHP, the “until”, its use is very simple, so in the next example we’ll see it with the for loop.

times = 4
now = 1
until now > times
puts "until #{now} of #{times} times"
now += 1
end
for i in 1..4
puts "Looping around 4 times (#{i})"
end

Take a look at the output, and check if it makes sense for you.

Both iterate the same amount of times. The for in Ruby is just like in PHP, but the syntax it’s a little bit cleaner. We don’t have to put the parenthesis in any of them, but we could, like in PHP. The only way we have to tell Ruby the loop ends, is the “end” reserve word

“All the conditional and loops finishes with the end reserve word”

Other loop, actually a Ruby style loop, is “times”. Yes, we say the number of times we want to repeat something, just like this:

5.times do
puts 'Impossible to be cleaner' # This will puts the string 5 times
end

We don’t have this loop in PHP, but it’s very useful if we know before the execution the exactly number of iterations we need.

Class Definition

Like PHP, Ruby is an object oriented language, which means we are going to have classes, methods and attributes. Take a look at this class in Ruby

The first difference we can notice here is the attributes definition. In Ruby we usually define them into the constructor or just with the sets and gets (we’ll see them later). And those attributes are defined by the @ just before its name, like @name. The definition of methods is also very simple, just with the “def” and “end” reserve words.

But like PHP, the class definition does nothing itself, so let’s use it (this code must be right after the class definition).

We have to notice two things in the example. First of all, we can’t access to an attribute without its getter. The other important thing is that the error is displayed after we run the program and see the result of calling “describe” (yes, like in PHP, most things happen when the script is running, so the execution goes on until there is an error or the script ends).

If we try to access to “owner” we’ve got an error. So we need something (hint: it will be a method) to get the content of the attribute.

Gets and Sets in Classes

The gets and sets (also known as getters and setters) are the methods to access and modify the private attributes of a class. As you might know is a very good practice to use them (just like in PHP). The difference here is that is almost obligatory, and we have a little help from the language.

With the attr_accessor we “declare” the set and the get method for the attribute. Actually, we usually declare the set and the method just for setting and getting the attribute. Despite this, there is a way to do more things in the set or the get method, but we won’t really need it. The point is we can access now to “name”!

“With attr_accessor we have the get and the set method at the same time”

Let’s put it all together!

In this last section, we are going to build a class with methods and use them, but we’ll use everything we’ve just learned. The good news here are we know PHP, so let’s use it to remember the Ruby’s syntax!

The class is going to model a factory and remember, take a look at the way we program it, and the differences with PHP, more than the use of the class.

class Factory
#sets and gets for all the attributes
attr_accessor :name, :creation_year, :use_of_floors
# The class constructor
def initialize(name,creation_year,use_of_floors)
@name = name
@creation_year = creation_year
@use_of_floors = use_of_floors
end
def description
puts "This factory is #{@name} and was created in #{@creation_year}"
end
def report_of_floors
@use_of_floors.each_with_index do |element,index|
puts "The floor number #{index} is used for #{element}"
end
end
end
a = Factory.new('Apple',1976,['Reception','Production','Offices'])
a.description
a.report_of_floors

And the output for this final script is:

Conclusion

This language, as many others, has many things we have to learn before we can call ourselves developers, but this tutorial covers the first steps using the knowledge of PHP to build actual programs. You can continue with more details in the official documentation.

I hope you liked it. Thank you for reading!

Share this:

This entry was posted
on Thursday, September 9th, 2010 at 09:08 and is filed under Tutorials.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback
from your own site.

I'm from Spain. I've been working in an Internet company for more than a year, I love everything about Internet, from designing to PHP.

This is a cool article, and it helps to get you started with developing with Ruby. Would you be able to create a tutorial on web development with Ruby? Doesn’t necessarily have to be Rails, as the framework often seems a bit cumbersome to me, I’m interested in plain old Ruby.

When I started out with Ruby and RoR, I was looking for some article/posts that would provide the information here, glad you guys wrote this, I wanted to but couldn’t find the time to come around! Kudos!

“echo is actually a language construct, but since you can use parenthesis it has not too much implications apart from it cannot be called using variable functions.”
there other differences about language constructs and about echo (echo has no return value, you cannot monkey patch it with namespace, since it not a function, you cannot disable it with disable_functions since its not a function, you cannot override a language construct, but you can override a function)
so I think it’s just easier to use print in the example, or replace the function with language construct.

I know Debian is not Linux, but most people who use Linux, has a distribution based on Debian, so that’s the main reason I typed that command. If you are using Linux with other distribution I’m pretty sure you know you should go to the official site.

And about echo, there are also some functions where the value they return is just useless, like print, which always returns 1. This is not the place where we should discuss the differences between echo and print, because this is about Ruby

Leave a Response

We do love friendly, well-constructed and respective comments. We do not love bitchy, stupid and disrespectful comments. Find something wrong in this post?, feel free to send us a note and we will fix the issue asap.