tags:

views:

134

answers:

2

I once found an article with the differences between how PHP and Ruby handle different types of variables matched with certain testing conditions (ie: isempty, isset, etc). How do they differ?

A: 

That's a very diffuse question. A major difference between Ruby and PHP is that Ruby is (mostly) strongly typed, whereas PHP is very weakly typed.

troelskn
+2  A: 

PHP/empty is pretty much the same as the Ruby equivalent, empty? For strings in Rails, the blank? method is preferred to empty?

# this is PHP
$bob = array();          # empty( $bob ) => true
$bob = array( "cat" );   # empty( $bob ) => false

$bob = null;        # empty( $bob ) => true
$bob = "boo"        # empty( $bob ) => false
$bob = "";          # empty( $bob ) => true

# this is Ruby
[].empty?           # => true
[ "cat" ].empty?    # => false

nil.empty?          # => NoMethodError
"boo".empty?        # => false
"".empty?           # => true

PHP/isset can be replaced with has_key? for the Hash object. For the general local variable usage Ruby instantiates variables as nil when they are referenced in the code, so the only easy thing to check for is whether or not they are nil?

EDIT

You can also use the defined? keyword to duplicate the PHP usage of isset for local variables.

#PHP

isset($bob);        # => false
$bob = "foo";
isset($bob);        # => true

$bob =  array();
isset($bob['cat']);  # => false

$bob =  array( 'cat' => 'bag' );
isset($bob['cat']);  # => true
isset($bob['dog']);  # => false

#Ruby
bob                  # => nil
defined?(bob)        # => false
bob.nil?             # => true
bob = "foo"
bob                  # => "foo"
bob.nil?             # => "false"
bob = {}
bob.has_key? :cat    # => false
bob = { :cat => 'bag' }
bob.has_key? :cat    # => true

One thing to be careful of: In PHP, an empty string or a numeric 0 will evaluate to false in an if statement. In Ruby, only nil and false evaluate to false in an if statement. This necessitates the addition of two more boolean inquiry methods, blank? and zero?. These methods are mixed in to the String class as part of a Rails application. Freestanding versions of them may be found on Facets.

austinfromboston