Ruby on Rails - Ruby Operator Precedence - Parentheses -
the following code results in error
example 1
if params[:id] == '2' || params.has_key? :id abort('params id = 2 or nothing') end syntax error, unexpected tsymbeg, expecting keyword_then or ';' or '\n' if params[:id] == '2' || params.has_key? :id
however, switching conditional statements || adding parentheses works 100%.
example 2
if params.has_key? :id || params[:id] == '2' abort('params id = 2 or nothing') end
example 3
if (params[:id] == '2') || (params.has_key? :id) abort('params id = 2 or nothing') end
can explain me why example 1 result in error ?
thanks
your problem happening at:
params[:id] == '2' || params.has_key? :id
which can simplified to:
:foo || some_method :bar
which causes same error. expression in principle, ambiguous between
(:foo || some_method) :bar (1)
and
:foo || (some_method :bar) (2)
when expression ambiguous, resolved other factors. 1 factor, operator precedence tells nothing here disambiguating between (1) , (2). next factor linear order. since ||
appears before argument application ()
(omitted) in expression in question, former applies before latter. therefore, expression interpreted (1). since (:foo || some_method)
parsed expression, there 2 expressions next each other. ungrammatical, as:
:baz :bar
is ungrammatical.
in fact, if switch order as:
some_method :bar || :foo
then, interpreted as
(some_method :bar) || :foo
for same reason, , syntax error disappear.
also when resolve ambiguity explicitly using parentheses indicate argument application:
:foo || some_method(:bar)
then there no ambiguity needed resolved, , syntax error disappears.
Comments
Post a Comment