From: Eivind Eklund Date: 2007-06-22T19:24:21+09:00 Subject: Re: avoiding nil.methodcalls short and cheap 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 > ) > 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? > > Thanks, > .tr! > > -- > Posted via http://www.ruby-forum.com/. > > -- Hazzle free packages for Ruby? RPA is available from http://www.rubyarchive.org/