From: Pit Capitain Date: 2004-05-20T10:52:42+09:00 Subject: Re: Zero is true ... whoda thunk? David Alan Black wrote: > Pit Capitain writes: >>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?" > 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. That's why I made the distinction between testing "normal conditions" (true / false) and testing the outcome of a method (valid object / no object). I counted predicates (boolean methods) like nil?, zero?, empty? as "normal conditions" to be tested with the true / false semantics. The "valid object / no object" semantics don't make sense for predicates. > 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.) Maybe I didn't find the right words. Of course returning nil from a method is "valid" in the sense of "it is no exception". For example, I read the match method as "give me a match" and the result nil as "sorry, I can't". As you said, you can't reasonably return a match object for "no match". On the other hand, select alias find_all to me means "give me a list of all elements that...". Even if there are no such elements, the method returns a list. It is empty, but it is a list, a valid result. Because select always returns a valid result, it doesn't make sense to interpret this result as a condition. If you wanted to make a boolean test (whether there exist matching elements or not), you wouldn't use select aka find_all, but find. Here it makes sense to ask "did you really find something?", and here again the result nil means "no, I didn't". (If you're only interested in the test result and not in an actual matching element, you could use the predicate any?, which would show the intention even better.) To summarize in other words: there are the obvious tests for boolean conditions including predicates (true / false) and an implicit test for success / no success (not-nil / nil). Does this make more sense? Maybe not, it's 03:50 AM... Regards, Pit