Empty Variables
-
One of the more confusing differences between Ruby and PHP is the different way in which the languages treat empty variables when evaluating statements.
The chart below shows the most common scenarios you may encounter. We have several similar charts in the Rails for PHP Developers book with other handy information.
PHP if ($x) empty($x) $x = "";FALSE TRUE $x = null;FALSE TRUE $x = array();FALSE TRUE $x = false;FALSE TRUE $x = 0;FALSE TRUE $x = "0";FALSE TRUE Ruby if (x) x.empty? x.blank?** x = ""TRUE TRUE TRUE x = nilFALSE u/m * TRUE x = []TRUE TRUE TRUE x = {}TRUE TRUE TRUE x = falseFALSE u/m * TRUE x = 0TRUE u/m * FALSE x = "0"TRUE FALSE FALSE * NoMethodError: undefined method ** Only Available in Rails While PHP evaluates all empty variable as
false, Ruby only evaluatesnilandfalseto befalse. Some Ruby objects have anempty?method, but this is not always as useful as you might expect. The method is only available on some objects, and callingnil.empty?orfalse.empty?will result inNoMethodError.The Rails framework adds a consistent method named
blank?that exists on all objects as a single way to check if a variable contains a blank object. Rails has also very recently added a correspondingpresent?method, which is equivalent of!blank?Handling Zero
Handling zero values often trips up beginning Ruby programmers. This cause of this confusion is best demonstrated by the following two code snippets.
PHP
$num = 0; if ($num) { // This not evaluated. }
Ruby
num = 0 if num # This is evaluated! end
Refer to the chart above as you read the snippets. While this may seem counter intuitive coming from PHP, for the most part it’s not a problem.
In Ruby code, we typically know when we’re working with numbers, or we can cast to them. We can then simply do something like these examples:
Ruby
num = User.count if num > 0 puts "there are some users" end if num.zero? puts "no users here" end
Similarly, it is important to note that zero (
0and"0") evaluates totrueusing0.blank?.


2 comments
comment by lowell 24 Sep 08
“Similarly, it is important to note that zero (0 and “0″) evaluates to true using 0.blank?.”
of course.. in ruby, everything but nil and false itself is true.
comment by Custom PHP 12 Nov 08
Might mess someone up if they are going back and forth or working on PHP apps while working on Ruby apps.
Post a comment