Tuesday, March 4, 2008

Fun with Ruby Conditional Evaluation

The first in a series of postings for the unwary Ruby Newbie (Rubie?).

Is a numeric value of 0 true or false? To a C or Perl programmer it's obviously false. In Java it's a trick question (try it). But even those who've never programmed in C or C++ seem to share a general expectation of "false, duh."

What about Ruby? It's easy enough to find out. We'll use irb (for "interactive ruby") to put the question to the interpreter directly:


[chrisa@doppio ~]$ irb
irb(main):001:0> if (0) then puts "true" end
true

Which is to say that any numeric value will test true. How about an empty string?

irb(main):001:0> if ("") then puts "true" end
(irb):1: warning: string literal in condition
true

Well, that's a little bit friendlier but still, I can see getting quietly horked by that one. Contrast this with Perl's behavior. The interactive debugger is a bit less friendly, so we just execute the test directly from the command line:


[chrisa@doppio ~]$ perl -e 'if (0) {print "true\n"} ;'
[chrisa@doppio ~]$

[chrisa@doppio ~]$ perl -e 'if ("") {print "true\n"} ;'
[chrisa@doppio ~]$

Doesn't quite match the "Principle of Least Astonishment" pattern...

No comments: