I’m currently learning Ruby. In this post I’ll list some pitfalls for programmers coming from PHP that would probably cause some confusion if you aren’t aware of them.
This list is by no means complete, while I learn Ruby I’ll very probably encounter more gotchas, which I will blog about, too.
Anyways, here we go, the incomplete list of things Ruby does differently than PHP:
1. Arrays are continuous
As a PHP programmer, you’re used to, for example, put User-objects into an array with the index being the user id:
1 2 3
Now you have an array with one element containing an User. Let’s do the same in Ruby:
Do not do it like that in Ruby!
If user_id is 9999, the above code will create an array of 10.000 elements, the last of them containing the User, all other elements containing nil!
Imagine having user ids in the range of millions…
Instead you must use hashes, like so:
This will create a hash containing only one element, the User.
2. Zero is not falsy
In Ruby only nil and false are false, everything else evaluates to true!
This is of course a good thing but in PHP this is something you’re probably used to do frequently - but it won’t work in Ruby!
3. The keywords private and protected
In Ruby any methods which are defined as private are not visible from outside the class but they are still visible to subclasses of the class containing the private method!
However, a private method is not visible to instances of the same class.
Methods that are protected have the same visibility as private methods - except that a protected method is visible to instances of the same class.
So by using private and protected you do not influence the visibility of methods for subclasses but their visibility to instances of the same class. In PHP “private” means “private to this class” while in Ruby it means “private to this instance”.
Here’s an example illustrating showing how private and protected change the visibility of methods from within instances of the same class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
Oh, and in PHP both private and protected methods can always be accessed from within instances of the same class, there’s no way to prevent that.
4. There’s no static keyword
If you’re looking for static in Ruby, well, stop looking.
This keyword doesn’t exist.
However, what exists instead, is the concept of class methods. Class methods are similar to static methods, in that they can be called without having to instantiate the class.
Explaining what class methods are, is out of the scope of this blog post but here are two blog posts about them from other authors:
I hope this list of differences between Ruby and PHP will help in your mission to learn Ruby and prevent you from shooting yourself in the foot.
I will almost certainly find more gotchas, thus I’d suggest you subscribe to my blog so you won’t miss them.
Anyways, have fun learning Ruby - I sure have! ;)
Review: Eloquent Ruby