PHP to Ruby: Lesson 2

March 22nd, 2009

In the first lesson we went over basic similarities of Ruby and PHP. Lets go over some more.

The Basics

Its essential to know what type of data you’re working with. Whether its a string, integer or an array, we need to know what type of data we’re about to manipulate.

PHP has the following functions is_array(), is_bool(), is_integer(), is_object(), is_string(), and many more.

Ruby also provides this functionality. Remember from the first lesson, Ruby is an object-oriented language so data type checking will be done with the method is_a?. Here are some examples:

1
2
3
4
5
6
# PHP
if(is_string($var))
...

if(is_integer($var))
...
In Ruby:
1
2
3
4
5
6
7
8
# Ruby
if var.is_a? String
...
end

if var.is_a? Integer
...
end

PHP is very powerful when working with arrays. A few useful functions are array_keys(), array_values(), explode() and implode().

For Ruby, in the same order, the methods are keys, values, split and join.

1
2
3
4
5
6
7
8
# PHP
$var = array( 'my',=>1, 'php'=>2, 'hash'=>3 );

$keys = array_keys($var); # using array_keys()
$values = array_values($var); # using array_values()

$new_array = explode(' ','my php array'); # using explode()
$new_string = implode(' ', $new_array); # using implode()

And for Ruby:

1
2
3
4
5
6
7
8
9
10
11
# Ruby
var = { 'my'=>1, 'ruby' =>2, 'hash'=>3 }

keys = var.keys # using keys method
values = var.values

new_array = 'my ruby array'.split(' ') # using split method
new_string = new_array.join(' ')

# splitting a string option 2
new_array = %W(my ruby array)

Hope this was helpful.

Leave a Reply