From: "David A. Black" Date: 2009-02-22T05:18:55+09:00 Subject: Re: why not check for nil? Phlip wrote: > David A. Black wrote: > >> Definitely use #nil? if you want to know whether something is exactly >> nil. There are certainly a lot of unnecessary calls to #nil? out >> there, but it doesn't follow that it can never be right to test for nil. > > Let's call this the "non-suicidal Samurai Principle". Either return > victorious, or return empty-handed. (And don't waste my expense training > you, duh!) > > How many times have we written... > > def samurai > blah and blah or blah > end > > if samurai > ... > > ...and then never bothered to check - even with unit tests, whether a > failing samurai() call returned a nil or a false? Ruby's break with > incorrect tradition - letting 0 be true - cleaned up a whole lot of > clutter. .index() can easily distinguish "found at 0 index" from "not > found". But this means we no longer always need to track which of those > blah() calls returns a nil, which a false, and which one the boolean > short-circuiting collects for us. > I didn't say you should always do it, simply that if you want to know whether an object is exactly nil, use #nil?. If you don't, don't :-) There's an interesting case of nil overloading that I've never seen any very nice workarounds for, though it probably occurs rarely if at all: a = [1,2,3,nil,"abc"] r = a.find {|e| !e } r will be nil -- but it will also be nil if a doesn't contain nil. Fortunately not an everyday problem, but an interesting case of difficulty distinguishing found from not found. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) Ruby Training Atlanta! April 1-3, http://www.entp.com/training/atlanta09