From: Michal Suchanek Date: 2007-06-22T20:12:45+09:00 Subject: Re: avoiding nil.methodcalls short and cheap On 22/06/07, Eivind Eklund wrote: > On 6/22/07, 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 > > Variations using just logic operators and conditionals - I think the > last two are probably best (though it vary by context) > > # Short, unclear > textvalue = xmltag.get_text > textvalue &&= textvalue.value > > # With if > textvalue = textvalue.value if textvalue = xmltag.get_text > > # Longer, clearer > if textvalue = xmltag.get_text > textvalue = textvalue.value > end > > # Re-using the variable, one-line > textvalue = xmltag.get_text and textvalue = textvalue.value > > # With new variable, possibly the cleanest > textvalue = (text = xmltag.get_text and text.value) > > # You can also redefine the object in question > def xmltag.get_text_value > text = get_text && text.value > end > textvalue = xmltag.get_text_value > I would avoid code that relies on logical operators to preserve values. That is any code that uses logical operators and would break if you put !!() around the expression is quite dodgy in my book. Thanks Michal