Tuesday, March 4, 2008

and (&&) operand

I found the following block in routing.rb of rails framework.
routes.each do |route|
result = route.recognize(path, environment) and return result

I didn't understand this block at all. So I posted this in the Ruby mailing list. The good folks at the group answered me back immediately with some good examples. Here is the link:

To summarize:
If the first operand (we can even call it a statement), i.e. result = route.recognize(path, environment) retuns true then the following things would happen:
  1. 'result' variable contains the result of the recognize statement (which is a hash)
  2. The second operand (statement) gets evaluated which in turn ends the block by returning the result variable
If the first operand returns false then nothing happens so the loop continues.

But what is tricky in the statement "result = true and x = 20" is that 'result' contains true and not 20. Which means the first operand is also doing an assignment. I initially thought result will contain 20 because that's return value of the second statement.

Here is another explanation of the same subject:

Super stuff. Ruby Rocks.

No comments: