We've looked at the differences between Ruby and PHP arrays before. Now lets compare PHP arrays and Ruby hashes. They should be similar as all PHP arrays are implemented as hashes. There is however a crucial difference that can trip you up if you are switching from one language to another.
Referencing an index that hasn't been set is an error in PHP, but not in Ruby.
In PHP, retrieving a value for an index that you haven't used is a warning. Although warnings can be turned off it is best practice to develop with them turned on.
1 2 3 4 5 6 7 8 9 10 11 |
|
In Ruby you can set a default value for all keys that have not set a value. By default this value is nil.
1 2 3 4 5 6 7 8 9 10 |
|
Ruby hashes are unordered (up to version 1.8). PHP arrays have an internal order seperate from their index.
When you loop through a PHP array, the values will be returned in the order they were added.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
In Ruby 1.8 hashes are unordered, they could be retreived in any order that ruby decides is best. Ruby 1.9 changes this so that it works in the same way as the PHP example above.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Is there anything that has been missed? Add a comment below.