From: Trans Date: 2007-06-23T00:48:39+09:00 Subject: Re: avoiding nil.methodcalls short and cheap On Jun 22, 5:53 am, 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? The conceptually simplest is: get_text = xmltag.get_text textvalue = get_text.value if get_text But as you will note, it takes up two lines. Of course you can always fix that: get_text = xmltag.get_text; textvalue = get_text.value if get_text Even so, I often write this as: if get_text = xmltag.get_text textvalue = get_text.value end Simply b/c I often find long one liners unpleasant to read. However, I just want to point out that if there is no get_text, than textvalue is not being assigned at all. Unless you have previously set textvalue to a default, that could lead to an undefined local variable error. So you might consider: textvalue = (get_text = xmltag.get_text) ? get_text.value : nil T.