M
Michiel de Mare
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?
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?