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.

  • Windows: Download the package from the official web: Ruby Downloads.
  • Mac OS X: Preinstalled.
  • Linux: Just type: “sudo apt-get install ruby-full”.
  • Other Operating Systems: Go to the official page Ruby Downloads.

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.

# Simple array with 3 elements
animals = ['dogs', 'cats', 'spiders']
puts animals[2] # third element

# Another way to create an array
cars = Array.new
cars &lt;&lt; 'BMW'
cars &lt;&lt; 'Toyota'
cars &lt;&lt; 'Ford'
puts cars[0]

# Hash (or array with not integer keys)
h = Hash[&quot;this_is_a_key&quot;, 100, &quot;other_key&quot;, 200]
puts h['other_key']

The output is:

Simple Array

Pretty simple, right? Well, besides of those methods we have some more for working with arrays, in PHP you have similar ways to get the same data, but in Ruby is even easier.

animals = ['dogs', 'cats', 'spiders']

puts animals.first # Output: dogs
puts animals.last  # Output: spiders
puts animals.length  # Output: 3

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:

Each in Ruby

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.

Loops Ruby

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

# define the class company
class Company
  def initialize(name, owner)
    # attributes of Company's class
    @name = name
    @owner = owner
  end

  # method new_product
  def new_product
    puts 'The new product is coming out!'
  end

  # method describe
  def describe
    puts "Hi, I'm #{@owner} and my company is #{@name}"
  end
end

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).

# class company definition
# ...
comp = Company.new('Free Cars', 'Ray')
comp.describe #Output: Hi, I'm Ray and my company is Free Cars

# Error in 3, 2, 1...
puts comp.owner #Output: NoMethodError: undefined method ‘owner’

The output will be:

Error in class

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.

class Company
 attr_accessor :name # Set and Get in a line
 def initialize(name, owner)
    # attributes of Company's class
    @name = name
    @owner = owner
  end
end

comp = Company.new('Free Cars', 'Ray')
puts comp.name
comp.name = 'Old Cars'
puts comp.name

The output, now without errors:

Class without errors

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:

Final Example


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!

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.

About the author Published by Jose

24 Responses »

  1. Great tut!

    puts ‘Impossible to be cleaner’

  2. 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.

  3. Perfect to step into Ruby! Thanks for this post. It’s the first thing I’ll read when starting with Ruby 🙂

  4. Congratz, its a great post, but i missed the examples in PHP too, for code comparisson..

  5. thanks, always wanted to know what this RUBY is. thanks again

  6. Unlike php, ruby was built from the ground up to be an object oriented language. In php it was tacked on as an after thought.

    Also, puts != echo

    puts = echo “” . PHP_EOL;

    print == echo (in that it does not add a new line to the output)

  7. get tutorial! i’m considering writing my next app in ruby.

  8. Great article! Must get studying 😉

  9. Check out http://railsforphp.com/ for a great reference of Ruby/Rails equivalents for PHP functions/methods.

  10. 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!

  11. I’ve had to stop in the beginning of your article. Although this may (erroneously, IMO) seem irrelevant to some, it’s a major (and kinda common) mistake:

    ‘The echo function of PHP is �puts� in Ruby. We …’

    Echo is NOT a function, it’s a language construct. Ironically the documentation URL follows a standard where the “function” word is used, but please read:

    http://docs.php.net/manual/en/function.echo.php

    TIA,

    • Hi Galvao,

      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.

      Thanks for the comment, and please, read the article 😉

  12. “Linux: Just type: ‘sudo apt-get install ruby-full'”
    Linux != Debian

    “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.

    Tyrael

    • Hi Tyrael,

      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 😉

      Thanks for the comment.

      Regards.

  13. apt-get is packacged with Red Hat or CentOS, 2 very prominent flavors of Linux. Before posting install instructions for Linux, be sure to note which distributions you are referring to,

  14. Nice post, really helped me understand Ruby’s syntax better.

    “Like PHP, Ruby is an object oriented language”

    … PHP isn’t object-oriented 😛

    • Hi Andrew, thanks.

      And please, see the paradigms of PHP here: http://en.wikipedia.org/wiki/PHP

    • @Jose

      The point I was making is that native types in PHP aren’t objects. Thus, I don’t consider PHP an object-oriented language; PHP isn’t oriented towards objects at all.

      I think something like “object-supportive” language is more accurate.

      Unfortunately, I couldn’t stick with Ruby’s syntax and will likely move to Java or more specifically Groovy as my second language.

  15. Nice website for PHP developer resources