The very basics
The Ruby language is object-oriented.
PHP is not object-oriented, but has objects. Ruby’s object-oriented nature results in some areas of it’s syntax to look very much like JavaScript.
PHP’s
echo is
puts in Ruby.
PHP uses semicolons. Ruby uses semicolons, but only in specific cases. For clean, readable code, assume you won’t be needing semicolons. Lets being…
The Basics
PHP creates arrays and hashes with the same function
array().
1
2
3
4
5
6
|
# PHP
$array = array('my', 'php', 'array');
$hash = array(
'my_index'=>'my_value',
'my_second_index'=>'my_second_value'
); |
Ruby handles arrays and hashes separately.
1
2
3
4
5
6
|
# Ruby
array = ['my','ruby','array']
hash = {
'my_index'=>'my_value',
'my_second_index'=>'my_second_value'
} |
Take note that Ruby creates arrays and hashes in the same syntax as JavaScript. Also note that there is no semicolon. Ruby doesn’t use them unless multiple commands are on the same line. That can lead to messy code or for loops so we’ll get into that later.
PHP uses curly brackets for blocking multiple commands and no curly brackets for single commands.
1
2
3
4
5
6
7
8
|
# PHP
if($is_php)
echo "Yes this is PHP"; # single command
if($is_php) {
echo "Yes this is PHP"; # first command
echo "Its great!";
} |
Ruby uses do and end for blocking multiple commands and curly brackets for single command blocks.
1
2
3
4
5
6
7
8
9
|
# Ruby
if is_ruby { puts "This is ruby!" } # single command
puts "This is a backwards if statement" if is_ruby # variation of single command
if is_ruby do
puts "This is ruby!" # first command
puts "Its awesome!" # second command
end |
Still pretty basic
PHP has the
foreach() function.
1
2
3
4
|
# PHP
$array = array('this','is','a','php','test');
foreach($array as $el)
echo "$el"; |
Ruby has an each method.
1
2
3
4
5
6
7
|
# Ruby
array = ['this','is','a','ruby','test']
array.each do |el|
puts el
end
array.each { |el| puts el } # the single lined version |
Another Javascript similarity. The method each should look familiar to anyone that has used any of the popular Javascript frameworks Prototype, Mootools, and jQuery.
Ruby and the web
One of Ruby’s best web friends is eRuby (embedded Ruby). eRuby will make the PHP to Ruby transition that much smoother. For example:
1
2
3
4
|
# PHP
<? if($is_php) { ?>;
PHP is great!
<? } ?> |
And with eRuby:
1
2
3
4
|
# Ruby
<% if is_ruby do %>;
Ruby is awesome!
<% end %> |
That will wrap up this entry, but there is more to come.
Leave a Reply