It’s been a while I know, and I am aware that some of you are chomping at the bit to read reason #5. Apologies for the wait, but some of us have work to do, and a mammoth side project to complete, which by the way, is coming along nicely.

Before I start on reason #5, I want to mention a couple of posts in a similar vein to my series.

Andy Jeffries “4 Reasons why Ruby syntax is better than PHP’s” is a straight to the point article all about the strengths of Ruby’s syntax over PHP. If after reading his post, you still think syntax doesn’t matter, then you are a lost cause, and beyond help of any kind!

Another post I actually read a while ago, but forgot all about until I was pleasantly reminded of, is Bitcetera’s “10 Reasons why PHP is still better than Ruby“. Read it carefully all the way through, as it is a great read.

Now, we get to Modules in Ruby, again, a feature that has no direct equivalent in PHP. Modules are very similar to classes, in fact they are written in much the same way:

RUBY
  1. module Animal
  2.   def name
  3.     "Dog"
  4.   end
  5. end

So what are they used for? Well, modules are generally used for two purposes; creating namespaces and mixins. I’m sure (and I hope) that you all know what namespaces are. But you probably have no idea what a mixin is. Well I’ll get to that in a bit. Let’s quickly talk about how Ruby uses namespaces.

Let us imagine that we have been charged with cleaning up and re-organizing our code, and we have a lot of it. Normally in PHP you might simply stick this code in a file and include it wherever you need it, but what if you have two methods or constants that are named the same? Some developers have worked around this by separating different class package names with underscores. This solution solves the immediate problem and also works conveniently with autoloading in PHP. It can, however, leave us with some really long class names.

Let’s imagine we have two classes that define a Document class. In PHP we would probably prefix each class name with the document type:

PHP
  1. class XML_Document {
  2.   public function __construct() {
  3.     print "new xml document\n";
  4.   }
  5. }
  6. class PDF_Document {
  7.   public function __construct() {
  8.     print "new pdf document\n";
  9.   }
  10. }
  11. $xml = new XML_Document;
  12. $pdf = new PDF_Document;

Ruby would achieve the same thing like this:

RUBY
  1. module XML
  2.   class Document
  3.     def initialize
  4.       puts 'new xml document'
  5.     end
  6.   end
  7. end
  8. module PDF
  9.   class Document
  10.     def initialize
  11.       puts 'new pdf document'
  12.     end
  13.   end
  14. end
  15. xml = XML::Document.new
  16. pdf = PDF::Document.new

Now I know that the as-yet-to-be-released PHP 5.3 will introduce namespaces, but come on! Have you actually seen how PHP namespaces are created and written?! WTF!? Using slashes just looks wrong! Slashes are used in directory paths, and that is where they should stay. And why should I have to declare my namespace at the very top of the file and no where else?

But the best thing about Ruby’s modules, is the ability to mix them into my classes, as if it was part of the original class code. Think of it as inheritance, but better. Everyone knows that in PHP and Ruby, a class can only inherit from one class at a time. To inherit from another class would involve you having to create a complicated chain of inheritance. Mixins eliminate that need. Just create a class, inherit from another class, and then mixin as many modules as you want.

RUBY
  1. module Movement
  2.   def run
  3.     puts "I'm running!"
  4.   end
  5.   def walk
  6.     puts "I'm walking a bit briskly!"
  7.   end
  8.   def crawl
  9.     puts "I'm so slowwww!"
  10.   end
  11. end
  12.  
  13. class Man
  14.   include Movement
  15.   def jump
  16.     puts "I'm bipedal and I can jump like a fool!"
  17.   end
  18. end
  19.  
  20. class Sloth
  21.   include Movement
  22.   def flop
  23.     puts "It's all a lie…all I can do is flop around."
  24.   end
  25. end
  26.  
  27. mister_man = Man.new
  28. mister_man.run
  29. →  I'm running!
  30.  
  31. mister_slothy = Sloth.new
  32. mister_slothy.flop
  33. →  It's all a lie…all I can do is flop around.

As you can see, this mechanism is very similar to inheritance in that you can use all of the mixin’s code. To use a mixin, simply define a module and then use the include keyword followed by the module’s name (note I said module; the include keyword has nothing to do with files or libraries like in PHP); from then on the class has access to all of that module’s constants and methods.

The above example really doesn’t do mixins justice, but it’s a very simple example to help demonstrate how they work. Modules are a very versatile tool in Ruby and allow us to extract and share common behavior in objects, and are another reason why Ruby is better than PHP (in my opinion).

I bet you thought I’d never get any more reasons out did ya? Well, today, I’m going to tell you all about IRB and the Rails command line debugger, both of which I use religiously.

One of the great pleasures of using Ruby, apart from the previous three reasons, and of course the following five reasons, is the wonder that is the Interactive Ruby console, or IRB. IRB is an interactive interpreter; which means that instead of processing a file, it processes what you type in during a session. It’s a great tool for testing Ruby code, and a great tool for learning Ruby.

Once you have Ruby installed on your computer, you will notice that the ruby command will do the same thing as PHP - it silently waits for a script to be streamed in on stdin. On it’s own, that’s not particularly friendly, or even that useful. But another command that is installed alongside Ruby, is the irb command. Start up your command line tool of choice, and simply enter these three immortal letters: irb. Then you will see this:

irb>

This is the irb prompt. Now all you do is simply type any ruby code, and it will show you the result of each and every expression as it is evaluated. Not sure how a method works, or can’t remember the output of a method? Then test it with IRB.

IRB lets you do things without having to fake out your controller. For example, in PHP, I’m forever using echo or CakePHP’s debug function to print out some useful info to the browser when debugging my code. But when developing with Ruby, I simply have my trusty IRB prompt ready and waiting for me to inflict world domination.

>> @george = Person.find_by_name('George')
>> @bob = Person.find_by_name('Bob')
>> @bob.friends << @george

Each of the above lines will be following by IRB echoing the result. So I can see exactly what is going on, and without me having to echo out data all through my code and to the browser.

This is actually very, very useful, and is a great way to test your code, or in fact any code at all. It’s even better if you are a command line freak like me.

What is even better, better (!?) is that Rails also has its own command line interpreter, which is basically an extension of IRB. What makes it a little different, is that when it is started up, it also loads all your Rails code. So you have instant access to your Rails models, which is also very handy. Just cd to your Rails app root, and run:

script/console

You are then shown a similar command line prompt to IRB, and can run any part of your Rails app code.

To wrap up reason #4, I want to tell you about one of the best things about developing with Ruby on Rails. It’s another extension of IRB, similar to Rails script/console, but is simply genius when debugging your Rails code.

There are several ways in which you can run your Rails app, but the traditional method is by using the the script/server script within your app. When run on the command line, this will start up a small web server, usually run by Webrick or Mongrel. Now I wouldn’t recommend this method when running your app in production, as there are much better, and more efficient ways to do so, but I use this all the time when developing or testing my app code.

Just cd to your Rails app root and run this on the command line:

script/server -u

Notice I appended a command line flag; -u. This tells the Rails server to start up in Debug mode. If you use Mongrel, this is what you will see:

=> Booting Mongrel
=> Rails 2.3.2 application starting on http://0.0.0.0:3000
=> Debugger enabled
=> Call with -d to detach
=> Ctrl-C to shutdown server

And the command line prompt will sit there blinking at you, waiting for you to load your app in your browser. So don’t keep it waiting, open up your browser, and go to http://localhost:3000, and you will be shown your Rails app in all its glory.

Now we get to the good bit. Open up the code of any of your controllers in your favourite IDE or text editor. Then type the word debugger within one of your actions. Then go back your browser and navigate to that page. You should the notice that the page does not appear to finish loading. That is because your debugger keyword within the action method, has paused the server until you tell it to continue.

Go back to your command line when you started the Rails server, and you will see a bunch of log data, following by what looks like an IRB prompt. That is effectively what it is. You can now type any Ruby code at that prompt, just like you would with IRB or script/console. But the beauty of this, is that you have access to all the variables and methods at exactly the same point in your code where you placed the debugger keyword.

So instead of having to type echo or print statements throughout your code, and running them through your browser to see the results. You can add the debugger keywork at the point where you want to debug, and use the command line to access your code in real time.

I really hope you got all that, as this feature has saved me hours and hours of time when debugging my code. I can honestly say that it is a life saver. You really should try it out now, or if you’re a little impatient, try it out in your browser for instant gratification. You should also check out Amy Hoy’s “Secrets of the Rails Console Ninja’s“.

Thanks again for sticking with me, and hold on to your pants for reason #5 where I will be talking about Modules; Ruby’s answer to namespaces. Which will lead me nicely onto another Ruby exclusive: Mixins!

P.S. I really appreciate everyone’s comments. Keep them coming.

So onwards and upwards! It appears that I still have a little work to do to convince you non-believers, so lets try again…

As previously mentioned, Ruby has some features that simply cannot be found in many other languages, let alone PHP. So here I introduce yet another one, and this is a biggie. But, please be warned that this one is a little harder to explain, so please be bear with me as I attempt to enlighten you.

Some of you may have heard of a language feature known in computer science as closures. If you have done any Javascript development, you should be familiar with closures, but may not know them by name. Ruby uses closures extensively, but refers to them simply as blocks. Which is actually easier to understand.

Many developers seem to think that blocks are somewhat of an obscure language feature, as they are pretty hard to find an equivalent in other languages. PHP is not the only language without support for blocks, but you should understand them, as they can be very useful, and quite powerful.

Although there is no direct translation of blocks in PHP, we can make some analogies to PHP that will help us understand and become familiar with blocks, and how they are useful. Lets use PHP to start a family:

PHP
  1. function start_family($num) {
  2.   echo "There are now $num kids in my family"
  3. }

PHP
  1. for ($kids = 99; $kids &gt; 0; $kids) {
  2.   start_family($kids);
  3. }

When the above code is executed, PHP evaluates the condition in the for loop, which calls the start_family function on each iteration.

The for and function keywords are built-in constructs of PHP, in the same way that semi-colons and curly braces are built-in. But there are very few control constructs in PHP that allow code to be attached to them within the curly braces. It’s not actually possible to add or create new control constructs in PHP, unless of course you fancy whipping up a PHP extension in C. (eurghh!)

To be fair, we could condense the above into the following, as there really would be no need to use a function within the for loop.

PHP
  1. for ($num = 99; $num &gt; 0; $num) {
  2.   echo "There are now $num kids in my family"
  3. }

So now lets do the same thing in Ruby:

RUBY
  1. 99.downto(1) { |num| puts "There are now #{$num} kids in my family" }

Slightly unfamilar syntax, but that’s nothing new when comparing Ruby with PHP. But the above is actually quite declarative. Lets break this down a little.

Hopefully, if you read reason #1 you will now know that 99 is an object, which has a method called downto. It’s pretty obvious that this method simply counts down from 99 to 1, and iterates through each number. It serves roughly the same purpose as the for construct in our PHP example. The odd looking bit between the curly braces, with the goalposts, is the block.

There are many similarities between the Ruby block and the PHP for loop. This is because the Ruby block is actually just a function in another form. A block is a function without a name, or an anonymous function. Yes I know PHP 5.3 will include some sort of support for anonymous functions, but again, it’s an afterthought.

A Ruby block can receive parameters in much the same way a method or PHP function can, but they are placed within the goalposts of the block. In our case, we place the number (num) of kids between the goal posts, and this becomes our one and only parameter. We can pass more parameters to the block, by simply separating them with a comma. If we don’t want to pass any parameters, then we leave off the goalposts completely. The rest of the block is executable code, just like any other Ruby method.

Every method in Ruby, whether it be a built-in one, or one that you create, can be passed a block. And that one simple fact is what makes blocks so powerful. In fact, if the downto method were written in pure ruby, it could look something like this:

RUBY
  1. class Integer
  2.   def downto(value, &block)
  3.     n = self
  4.     while n >= value
  5.       block.call n
  6.       n -= 1
  7.     end
  8.     return self
  9.   end
  10. end

So we reopen the Integer class, and redeclare the downto method. We then pass two parameters to that method. Pay particular attention to the second parameter: &block, as it is very important.

When a block is passed to a Ruby method, it can be captured in a variable. In fact, the code that we pass within the block to downto is converted into an object, and then stored inside a variable. The ampersand &block tells Ruby to store this block in a variable called block. The keyword self in this example refers to the object itself, which in this case is the integer 99.

Still with me? Good! Lets take our earlier example again, and apply it to the downto method that we just created:

RUBY
  1. 99.downto(1) do |num|
  2.   puts "There are now #{$num} kids in my family"
  3. end

Hold a second, the above code is different to our first example isn’t it? Yes it is, well spotted! Just as in everything in Ruby, you don’t need the curly braces. The use of the do keyword is usually used for larger blocks, that need to span multiple lines. But it does exactly the same thing.

When the downto method is called, it receives two parameters: value contains the number of kids we have, and block contains the block of code that will be run on each iteration.

The inside of our downto method should look familiar to you, as it is effectively doing the same thing as our PHP for loop. It just counts down from 99 to 1, using a while loop. Then on each iteration of the while loop, it yields control to the code that is passed in the block variable, by calling the block.call method. Any parameters passed to block.call, are passed in the same way to the goalposts in the block.

A little confusing I know, but I really wanted to explain how blocks work as well as I could, as they are becoming ever more useful to me, the more that I develop with Ruby.

To finish off, I really want to show you an awesome way that Ruby’s blocks are used. I won’t go into it too much though, as it leads on to another of my reasons. There is a Ruby library (Gem) called Shoulda which improves the Test:Unit unit testing library that is supported as standard in Ruby on Rails. Shoulda improves the language of your unit tests, and turns them into an almost human readable form. So here we have a test:

RUBY
  1. context "a User instance" do
  2.   should "return its full name"
  3.     assert_equal 'John Doe', user.full_name
  4.   end
  5. end

Now start from the beginning of that code and just read it out load. It may end up something like this “a User instance should return its full name“. Of course there is more in between, but what I am trying to convey is how expressive and readable the above code is. And that is because of the power of blocks.

Hope that helps a little. Keep the comments coming guys, and thanks for reading.

Well now then. My last post, or the comments in it, seemed to have stirred up a little hornets nest. I had my fair share of supporters and my fair share of thanks for my writings, but I also received a little criticism. I think I’ve covered most of those in the comments and also on Twitter, so I won’t say much more, other than to simply remind you all what I am trying to do.

In this little series of blog posts, my objective was to be as fair as possible when explaining my reasons why I think Ruby is better than PHP. But at the same time, this is not a comparison. Which means I won’t be pointing out PHP’s strong points - of which there are many. Also, this is my opinion, and no one elses, and I am entitled to that. And so to, are you guys.

And one last thing before I start reason #2. I want to say thanks to Chris Hartjes for his blog post earlier today. I made a comment on Twitter about lazy coders, being good coders, and he basically put me to rights, and explained what I was saying in much better terms, than I could ever do. But also, I do think he was a little harsh on me. Hear my other reasons first Chris. No hard feelings though.

Back to business. In todays post, I wanted to give more of a solid reason why I think Ruby excels over PHP. So I picked one that simply cannot be matched in any way by PHP. Add probably won’t ever be. But I would love to see this being made possible.

Re-opening in Classes is soooo Useful!

Both languages support the creation of classes as part of their object-oriented design. And they do so in much the same way. Both languages allow you to set method visibility with the use of public, protected and private declarations, and behave accordingly. Classes are written in a similar fashion:

PHP
  1. class Person {
  2.   public function greeting() {
  3.     return 'Hello you!';
  4.   }
  5. }

RUBY
  1. class Person
  2.   def greeting
  3.     'Hello you!'
  4.   end
  5. end

Very similar, but let me explain one thing. In the PHP example above, I returned the string “Hello you!” by prefixing it with the return keyword. Like this:

PHP
  1. return 'Hello you!';

But in the Ruby example, you may have noticed that there is no return keyword before the “Hello you!” string. It was just this:

RUBY
  1. 'Hello you!'

That works perfectly fine, and the “Hello you!” string will still be returned when calling the greeting method of the Person class. That is because Ruby will return the value from the last line of the method. You can use return if you want to, but you don’t have to.

So we’ve determined that writing classes is pretty much on the par in both PHP and Ruby. But, you may have accidentally redeclared a class in PHP, and received a nasty error:

PHP
  1. class Person {
  2.   public function greeting() {
  3.     return 'Hello you!';
  4.   }
  5. }
  6.  
  7. class Person {
  8.   public function greeting() {
  9.     return 'Hey, hey, hey!';
  10.   }
  11. }

Doing the above will give tell you PHP Fatal error: Cannot redeclare class Person. Everyone knows that you just cannot do that with PHP. And to be honest it seems to make sense for it to prevent this from happening. But Ruby actually allows you to do this. In fact, you are almost encouraged to reopen classes if and when needed.

RUBY
  1. class Person
  2.   def greeting
  3.     'Hello you!'
  4.   end
  5. end
  6.  
  7. class Person
  8.   def greeting
  9.     'Hey, hey, hey!'
  10.   end
  11. end

In the above case, no error will be returned. Instead, Ruby will simply redefine the greeting method in the first class, with the same method from the second class. So you get this:

RUBY
  1. p = Person.new
  2. puts p.greeting

Which returns “Hey, hey, hey!” and not “Hello you!

Oh no, here it comes. I can hear the cries now: “But that’s gonna cause untold problems and bugs in my code!”. Not if you use it wisely! Part of Ruby’s philosophy is to provide you with all the tools you need, then entrusting you to use that power with care. What was it Uncle Ben said to Peter? “With great power comes great responsibility.”

This type of feature may seem a little dodgy, but in practice it becomes extremely useful. It means that I can reopen any class that I want, at any time, which often leads to more manageable code.

But I’m not just limited to reopening my own classes. I can even reopen Ruby’s base classes. This is referred to as “Monkey patching”, and is usually frowned upon, as it is not very wise to be overriding the core of the language. But if used carefully and sparingly, we are able to add a little extra functionality to our app by extending a base class or two.

When it comes to Rails, Ruby’s base classes are extended quite a bit, especially within its ActiveSupport library, which reopens the String, Integer, and many other base classes. But it does so to add a lot of extra, and very useful functionality. It’s done so with care and attention.

For example, I want to know if an integer is odd or even, but Ruby provides no such method for doing so, so I write my own. But instead of writing a standalone function within my class, I can reopen Ruby’s Integer class like so:

RUBY
  1. class Integer
  2.   def odd?
  3.     self % 2 == 1
  4.   end
  5. end

and now I can call:

RUBY
  1. 3.odd?

which would of course return true. All I am doing is reopening the Integer class, and adding a new method.

“But what’s that question mark doing there? Is that part of the method name?” Actually, yes it is. In PHP, you can only use letters, number, and underscores in method and function names. But Ruby lets be a little more expressive, and use other characters such as ?, !, and even /. So in the odd example above, I ended the method name with a question mark, because what I am doing is effectively asking a question of the number. “Are you an odd integer?”. Which it replies with a true or false value. Neat hey?

One of the most powerful uses of reopening classes, is the plugin system available in Rails. We can use Rails plugins to extend and override nearly every part of Rails. Which is why there are thousands of Rails plugins. You can do pretty much anything you want.

So I hope I have provided a good, solid reason why Ruby is better than PHP, with a feature that simply cannot be achieved with PHP. It really is very powerful, that when used carefully, can save you a lot of time, and make coding with Ruby lots of fun. Which after all, that’s why we’re here isn’t it?!

Next time, I think I’ll talk about Blocks; yet another feature of Ruby that PHP cannot emulate.

So it seems that I didn’t provide the best of examples in my last post, when explaining why I chose Ruby on Rails instead of CakePHP for developing Codaset. So I decided that I will write 10 [solid] reasons, why Ruby is better than PHP. After all, that is why I chose it.

I already explained a little bit about the aesthetics of Ruby, and how you can write a method without the need for any curly braces or even parenthesis. So I think I will leave the aesthetics alone for a little bit.

What a wonderful Objectified world!

I think one of the most significant differences between Ruby and PHP, and perhaps the basis for a lot of other features of Ruby, is that everything in Ruby is an object. Even though PHP supports Object Oriented Programming, OOP was not even thought of when PHP started out. OOP was simply hacked into the language, and so is not a pure object-oriented language. That is because it uses primitive types; things that are not objects. We use primitive types all the time in PHP. Things like integers, floats and strings are all primitive types. Pretty much all we can do with them, is store data in them and pass them around. On their own, they do very little.

Ruby is a pure object-oriented language, and it was built like that from the start.

So why should I care? I hear you say. Well, because everything in Ruby is an object, everything accepts method calls, even nil. (nil is Ruby’s equivalent to PHP’s null.)  In PHP, a string isn’t smart enough to do anything on its own. If we want to get the length of a string, we would have to call a separate function, and pass the string to it:

PHP
  1. $my_string = 'Just another string';
  2. echo strlen($my_string);

With Ruby, we can ask the string directly, to tell us its length:

RUBY
  1. my_string = "Just another string"
  2. puts my_string.length

FYI: PHP variables always start with a dollar sign $, but Ruby doesn’t have this requirement. Yet another keystroke saved. Yay! You also may have noticed that we also don’t need to type the semi-colon ; at the end of each line in Ruby. You can, but you don’t have to, unless of course the above two lines are placed on the same line. In which case, the semi-colon will be needed to separate the two.

We could also write the above ruby code like this:

RUBY
  1. puts "Just another string".length

Chicken or Egg?

One of the biggest frustrations for me when it comes to coding in PHP, is the need to memorise the order of arguments to the language’s many global functions. I’ve been coding in PHP for over 10 years now, and I still have trouble remembering which argument comes first in a function call. Was it the chicken or was it the egg?

For example, let’s take the in_array function:

PHP
  1. in_array($chicken, $egg);

And then lets compare that with the array_push function, which takes its arguments in the reverse order:

PHP
  1. array_push($egg, $chicken);

Most of PHP’s array functions take an array as the first argument, but there are a few exceptions. Inconsistencies such as this can get very frustrating, and PHP is riddled with them. When you don’t know any differently, you tend to overlook these. But ever since I started working with Ruby, these little annoyances actually become big annoyances.

But this is the nature of PHP and it’s procedural programming design. Fortunately, Ruby solves this problem with object orientation. Lets look at Ruby’s equivalents to in_array and array_push.

First we create an array and assign it to the fruit variable:

RUBY
  1. fruit = ['apple', 'orange']

Then we check to see if 'banana' is in the fruit array. This is the same as PHP’s in_array function:

RUBY
  1. fruit.include? 'banana'

So the above obviously returns false, as 'banana' does not exist, or is not included in the fruit array. So lets push it in:

RUBY
  1. fruit.push 'banana'

And now fruit equals ['apple', 'orange', 'banana']

In Ruby, an array is an object, so if we want to push a variable into the array, we simply take that array and just call push. It needs only one argument, since the method is attached to the object on which it will operate. And we now have no source of confusion.

Not only does this help with remembering arguments, it also helps to organize the Ruby code space. Instead of having many procedural functions in a global space like PHP, Ruby packages all its methods nice and neatly into the objects that actually need them.

Of course, there are many more reasons why objectifying everything can help you, but these are some of the most notable. But I hope you can see that Ruby’s object-oriented nature actually makes life simpler.

In my next post where I explain reason #2 as to why Ruby is better than PHP, I will attempt to explain and show you one of the biggest differences, and the reason why developing plugins in Rails is so powerful.

Thanks for tuning in guys, and don’t forget to leave your comments. I’d love to know your thoughts and opinions.

Who is Developing with Style?

My name is Joel Moss, a web developer and all round nice guy, living in Manchester, England. I am currently working full time for ShermansTravel.com, but I fill whatever spare time I have with lots of good and wholesome "stuff"! Like developing my own ideas; such as Tooum, contributing to the excellent CakePHP framework, and doing more work for ShermansTravel.

So this is my blog - my soap box! Here I attempt to share my likes, my dislikes, and my opinions. As well as providing some occasional respite from the daily crap we all endure. Enjoy ;)

Hey, if you want to reach me, i'm available via email:joel[at]developwithstyle[dot]com, and AIM:joelkmoss.


Categories

Archives