0

I tried code like this in ruby:

if object && object.is? ball
   object.throw!
end

This resulted in a syntax error:

 unexpected tIDENTIFIER, expecting keyword_then or ';' or '\n'

I figure this is because && must have a higher "precedence" than a function call (I'm sorry, I don't know the correct terminology) and so Ruby essentially saw the statement as:

if (object && object.is?) ball
   object.throw!
end

which makes no sense and so a syntax error is in order.

This is further supported by the fact that this DOES work:

if object and object.is? ball
   object.throw!
end

I presume it is because the 'and' operator has a lower precedence than &&, so the "precedence" of a function call must be somewhere between && and 'and'.

However, in the precedence order tables I have seen before, function calls are not listed.

I would appreciate some insight into what is happening here, and perhaps some references to the ruby specification. I am not an expert in expression resolution, I am just interested in learning more about the processes, problems and theory behind this example of, no doubt, a wider topic

Matthew Sainsbury
  • 1,470
  • 3
  • 18
  • 42
  • *[The precedence built into Ruby can be overridden](http://www.techotopia.com/index.php/Ruby_Operator_Precedence) by surrounding the lower priority section of an expression with parentheses* so, `object && object.is? ball` can be as `object && (object.is? ball)`. – Arup Rakshit Feb 06 '14 at 13:54

1 Answers1

0

Because of Operator Precedence, you should either do:

if object && (object.is? ball)

or

if object && object.is?(ball)

The reason is "&&" and "||" have higher precedence than "and" and "or". Thus if you don't use parenthesis for the latter "object.is? ball", "object.is?" will be grabbed first by "&&". However, if you use "and" without parenthesis, it works fine, since it has lowest priority in this case:

if object and object.is? ball
Jing Li
  • 14,547
  • 7
  • 57
  • 69