From: Robert Klemme Date: 2007-03-21T22:05:15+09:00 Subject: Re: nil? with block On 21.03.2007 13:51, 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. Actually I am not sure about readability. Lines tend to grow pretty long that way. I would probably not use it. Also keep in mind that you will usually get an exception anyway since you're most likely calling a method that nil does not support. > 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: ... and probably slower than the current implementation as they add another boolean check. > 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? I am not so sure. But you can easily implement this with another method name so you don't have to change existing code's behavior. Also, nil values might be just only one reason to throw an exception so I am not sure about general usefulness. Yeah, I know - I'm a conservative skeptic. :-) Kind regards robert