|
| 1 | +--- |
| 2 | +layout: page |
| 3 | +title: To Ruby From PHP |
| 4 | +--- |
| 5 | + |
| 6 | +PHP is in widespread use for web applications, |
| 7 | +but if you want to use Ruby on Rails or just want a language that’s more |
| 8 | +tailored for general use, Ruby is worth a look. |
| 9 | + |
| 10 | +### Similarities |
| 11 | + |
| 12 | +As in PHP, in Ruby… |
| 13 | + |
| 14 | +* Ruby is dynamically typed, like in PHP, so |
| 15 | + you don’t need to worry about having to declare variables. |
| 16 | +* There are classes, and you can control access to them like in |
| 17 | + PHP 5 (`public`, `protected` and `private`) |
| 18 | +* Some variables start with $, like in PHP (but not all) |
| 19 | +* There’s `eval`, too. |
| 20 | +* You can use string interpolating. Instead of doing ”$foo is a $bar”, |
| 21 | + you can do ”#\{foo} is a #\{bar}”—like in <span |
| 22 | + class="caps">PHP</span>, this doesn’t apply for single-quoted strings. |
| 23 | +* There’s heredocs |
| 24 | +* Ruby has exceptions, like <span class="caps">PHP 5</span> |
| 25 | +* There’s a fairly large standard library |
| 26 | +* Arrays and hashes work like expected, if you exchange `array()` for |
| 27 | + `{` and `}`\: `array('a' => 'b')` becomes `{'a' => 'b'}`. |
| 28 | +* `true` and `false` behave like in <span class="caps">PHP</span>, but |
| 29 | + `null` is called `nil` |
| 30 | + |
| 31 | +### Differences |
| 32 | + |
| 33 | +Unlike in PHP, in Ruby… |
| 34 | + |
| 35 | +* There’s strong typing. You’ll need to call `to_s`, `to_i` etc. to |
| 36 | + convert between strings, integers and so on, instead of relying on the |
| 37 | + language to do it |
| 38 | +* Strings, numbers, arrays, hashes, etc. are objects. Instead of calling |
| 39 | + abs(-1) it’s -1.abs |
| 40 | +* Parentheses are optional in method calls, except to clarify which |
| 41 | + parameters go to which method calls |
| 42 | +* Instead of naming conventions, like underscores, the standard library |
| 43 | + and extensions are organized in modules and classes |
| 44 | +* Reflection is an inherent capability of objects, you don’t need to use |
| 45 | + `Reflection` classes like in PHP 5 |
| 46 | +* Variables are references. |
| 47 | +* There’s no `abstract` classes or `interface`s |
| 48 | +* Hashes and arrays are not interchangeable |
| 49 | +* Only `false` and `nil` are false: `0`, `array()` and `""` are all true |
| 50 | + in conditionals. |
| 51 | +* Almost everything is a method call, even `raise` (`throw` in PHP). |
0 commit comments