How do Ruby and PHP differ in their evaluation mechanisms?
PHP / empty
is pretty much the same as Ruby equivalent.For empty?
strings in Rails, the method is blank?
preferredempty?
# 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 general use of a local variable, Ruby creates variables as nil when they reference code, so the only simple check is whether or not they are nil?
EDIT
You can also use a keyword defined?
to duplicate PHP usage 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 note: in PHP, an empty string or a numeric value of 0 will evaluate to false in the statement if
. In Ruby, only nil
and false
evaluates to false in an if statement. This requires adding two more Boolean query methods blank?
and zero?
. These methods are mixed with the String class as part of the Rails application. Free versions of these can be found on Facets.
a source to share
This is a very diffuse question. The main difference between Ruby and PHP is that Ruby is (mostly) strongly typed whereas PHP is very weakly typed.
a source to share