From: David Alan Black Date: 2004-05-20T09:43:49+09:00 Subject: Re: Zero is true ... whoda thunk? Hi -- Pit Capitain writes: > Booker C. Bense wrote: > > _ I think this issue is a Licorice Test[1] for Ruby. To me it's > > fundamental to the entire point of Ruby. If you are really > > bothered by this, then maybe Ruby is not for you. For me, its > > one of the big reasons I really like Ruby. A Ruby in which > > zero was false would not be Ruby.... > > Agreed. > > Boolean values are used for what? To test a condition. A normal > condition like "x > 0" or "s.empty?" has a value of true or false. I > think there's no discussion about this. > > Besides those normal conditions Ruby has a shortcut for exactly one > special case: "did I get a valid result from a method call or not?" > In Ruby, this translates to "did I get a real object or nil?" (Of > course nil is an object as everything else in Ruby, but it has the > meaning of "no object".) > > You could code this condition as > > if !x.nil? > or > unless x.nil? > > but since it is so common, Ruby has the shortcut > > if x > > From this point of view, only nil can be treated as false. I'm not sure about these equivalencies, though. "if x" is not the same as "if !x.nil?", since they'll give different results if x is (the object) false. (I think that's part of why #nil? exists.) Also, in a case like Regexp#match, which returns nil on no-match, you're definitely getting a valid result (no match). And nil as a method return is not a Ruby-wide way of signaling failure; for example, Enumerable#select returns an empty array when it selects nothing. (I guess an empty MatchData object would be kind of paradoxical, since it should be a NoMatchData object.) (None of which bears directly on zero -- I'm just chattering :-) David -- David A. Black dblack@wobblini.net