Is there a reason why eval( “a = not a”) raises a syntax error
whereas eval( “a = !a”) works as I expected ?
Probably because the statement “a = not a” is also a syntax error
(regardless of the eval).
The ‘not’ operator has a lower precedence than assignment, whereas the !
operator has a higher precedence. Therefore the interpreter reads the
second form as “a = not” which is a syntax error.
If you really want to use the word form use: eval(“a = (not a)”), which
will take care of precedence.
See:
http://phrogz.net/ProgrammingRuby/tut_expressions.html#definedandorandno
t
and http://phrogz.net/ProgrammingRuby/language.html the section on
Boolean Expressions and table_18.4.
Hi,
OK, so precedence of: not, is lower than precedence of: =. Thanks.
Yet…
Is there a reason why eval( “a = not a”) raises a syntax error
whereas eval( “a = !a”) works as I expected ?
Probably because the statement “a = not a” is also a syntax error
(regardless of the eval).
The ‘not’ operator has a lower precedence than assignment, whereas the !
operator has a higher precedence. Therefore the interpreter reads the
second form as “a = not” which is a syntax error.
If you really want to use the word form use: eval(“a = (not a)”), which
will take care of precedence.
See:
Expressions
t
and The Ruby Language the section on
Boolean Expressions and table_18.4.
I now understand that thing are happening the way they are documented.
For the sake of curiosity, I would still like to know why things
were designed this way. A way that makes “not” rather useless to me
(besides the rare case where I would want to avoid a redefined !()).
i.e. why is “not” 's precedence lower than assignment’s one ???
Thanks
Jean-Hugues
···
At 14:56 31/03/2004 +0900, Mehr, Assaph (Assaph) wrote:
Web: @jhr is virteal, virtually real
Phone: +33 (0) 4 92 27 74 17
The “and”, “or” and “not” operators all have lower precedence. If you
need higher precedence, use “&&” “||” and “!”. The word-based boolean
operators are provided as a counterpoint to the higher priority symbol
ones. The lower precedence allows you to get away with less parenthesis
in certain situations.
*>> x = 23 == 23 && ! y = 42 == 23 #=> false
*>> [x,y] #=> [false, true]
*>> x = 23 == 23 and not y = 42 == 23 #=> false
*>> [x,y] #=> [true, true]
–Mark
···
On Mar 31, 2004, at 3:12 AM, Jean-Hugues ROBERT wrote:
For the sake of curiosity, I would still like to know why things
were designed this way. A way that makes “not” rather useless to me
(besides the rare case where I would want to avoid a redefined !()).
i.e. why is “not” 's precedence lower than assignment’s one ???