confused about andand

D

Dan Thomas

Hello,

I'm reverse engineering some code I inherited, and having a little
trouble understanding andand. I know that

a.andand(b)

is equivalent to

a && a.b

and yet I'm still having trouble understanding:

id = step.search("property[name=id]").first.andand["value"]

I would like to rewrite it using the "&&" notation, to have as a comment
in the code.

If you could write it out for me, it would help a lot. Thanks!
 
G

Gary Wright

and yet I'm still having trouble understanding:
=20
id =3D step.search("property[name=3Did]").first.andand["value"]
=20
I would like to rewrite it using the "&&" notation, to have as a = comment
in the code.
=20
If you could write it out for me, it would help a lot. Thanks!

I'm guessing that step.search() may return an empty list.

So .first will return

1) the first item in the list
or
2) nil if the list is empty

In the first case calling ["value"] will work because first returned =
something.
In the second case calling ["value"] will fail because first is nil.

The 'solution' is to use 'andand' to hide the 'failure' in the second =
case and just
return nil.

Here is a rewrite that might make this clearer:
first_item =3D step.search("property[name=3Did]").first
=20
if first_item
id =3D first_item["value"]
else
id =3D nil
end


Using the && operator that looks like:
first_item =3D step.search("property[name=3Did]").first
=20
id =3D first_item && first_item["value"]

The andand method is just a tidy way of wrapping up this logic. You =
really need the temporary variable to avoid repeating the complex =
expression when using the && operator (see how first_item is repeated?) =
and it is syntactically complex to do that for complicated expressions =
in a 'one-liner':
id =3D step.search("property[name=3Did]").first && =
step.search("property[name=3Did]").first["value"]

with a local variable to avoid re-evaluating the complex expression:
id =3D (f =3D step.search("property[name=3Did]").first) && f["value"]


It gets worse if you need additional steps:
id =3D (s =3D (f =3D step.search("property[name=3Did]").first) && =
f["value"]) && s.["another_value"])

vs
step.search("property[name=3Did]").first.andand["value"].andand["another_v=
alue"]



Gary Wright
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top