From: Phlip Date: 2007-09-08T04:29:25+09:00 Subject: Re: nil.to_s Nasir Khan wrote: > IMHO nil.to_s => "", nil.to_i => 0 and nil.to_a => [] are potential > sources > of confusion and bugs. nil is a potential source of confusion and bugs. Ideally, a method should not be called, or it should be called with only relevant data. That's the goal of your high-level designing; look up "Null Object Refactor" to learn good tips there. After you allow nils into your equations, you already have the potential source of confusion and bugs... > If anywhere in your code you have statement like > > x = y.to_s then you will have to be careful to replace it with > x = y.nil? ? nil : y.to_s Google for my illustrious street name, "relevant", and "relevance", all with separate sets of quotes (to prevent stemming). My projects use a cute little patch on NilObject which takes care of that exact situation: x = y.relevance > Is it just me or are there others who have also feel like this? Ruby's nil handling is exceptionally clean and useful, compared to other languages. Some, for example, allow 0 to behave as 'false'. That would be bogus in Ruby because 0 is not nil, and nil _does_ behave as false. So we allow statements like (x || '') to perform intuitively, without cluttering our methods up with excessive 'if' statements. The price of these conveniences is (x || '') is not as costly as it should be. Our programs should have fixed x before they got to this point. But Ruby gives the short-term bandaid a lower cost than the long-term cure. -- Phlip http://www.oreilly.com/catalog/9780596510657/ "Test Driven Ajax (on Rails)" assert_xpath, assert_javascript, & assert_ajax