From: "David A. Black" Date: 2007-03-21T22:04:51+09:00 Subject: Re: nil? with block Hi -- On 3/21/07, Michiel de Mare wrote: > If you have a long chain of method calls, but want to check some > temporary values for nils, for instance to raise an exception, > currently the easiest way is with local variables: > > e.g.: > > def zipcode_for_user(user) > address = user.personal_data.address > raise 'no address!' unless address > address.zipcode > end > > If "nil?" is extended to accept a block, and to return self (for > Object) and the result of the yield (for NilClass), the following > notation becomes possible: > > user.personal_data.address.nil?{ raise 'no address!'}.zipcode > > This is more concise, and (I think) also more readable. The flow of > the program isn't broken by the nil-check. Apart from raise > statements, it would make sense to use return statements in the > blocks. > > The implementation is trivial: > class Object ; def nil? ; block_given? ? self : false ; end ; end > class NilClass ; def nil? ; block_given? ? yield : true ; end ; end > > Do you think this is a good idea? No, I don't like it. It's unidiomatic for a ?-method to take a block, and also for a block to serve as a conditional branch. I'd rather see it unrolled. I understand the reasoning behind it, but it ends up being idiosyncratic in its semantics. David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)