From: Trans Date: 2007-06-23T23:09:40+09:00 Subject: Re: avoiding nil.methodcalls short and cheap On Jun 23, 9:17 am, Daniel DeLorme wrote: > Thorsten Rossner wrote: > > Hi, > > > I often have to check if a methodcall A is not returning nil before > > calling another method on the return value of the methodcall A. I'm > > looking for a short and cheap (avoiding to call method A two times like > > in this example where xmltag.get_text is method A: > > textvalue = xmltag.get_text.value if xmltag.get_text > > ) > > The ideal solution would be a oneliner with only little complexity > > calling method A just one time. Am I using the wrong approach here > > anyway? > > This the solution I use in *my* code for this common problem: > textvalue = xmltag.get_text.ergo.value > > This is my personal solution and I've never seen anyone use something > like this, so it may not be a "common and accepted idiom" but it works > well for me. YMMV > > code for "ergo": > > class NilClass > def ergo > @blackhole ||= Object.new.instance_eval do > class << self > for m in public_instance_methods > undef_method(m.to_sym) unless m =~ /^__.*__$/ > end > end > def method_missing(*args); nil; end > self > end > @blackhole unless block_given? > end > end > > class Object > def ergo > if block_given? > yield(self) > else > self > end > end > end Interesting... I like this. Nice use of fluent / magic dot notation. This is a good use case for Functor too (see Facets): class NilClass def ergo @blackhole ||= Functor.new{ nil } @blackhole unless block_given? end end One question, I'm not sure what you expect to be returned if a block is given. Besides that one issue, I'd like to add this to Facets and credit you. T.