Trans
6/22/2007 3:49:00 PM
On Jun 22, 5:53 am, Thorsten Rossner <ross...@gmx.de> 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.