From: Ben Brightwell [mailto:neogia4@gmail.com]
# The way I see it (and also the way I practice it today) is to always
# always always use "&&" or "||" over "and" or "or", respectively.
# The words "and" and "or" are lower in the order of operators than the
# symbols "&&" and "||". This is intentional for beginner
# programmers to be able to "read" the code rather than work out the
# logic of the code.
Ben thanks, but i'm not convinced. It still does not answer why it is not allowing in case-when clause yet allowing it in if-elsif,
The point is that case/when has different precedence to if/elsif. The Pickaxe precedence table doesn't mention case/when, but the order of the others is given as:
&&
or
and
if
So 'if' has the lowest precedence and any combination of and/or/&&/|| will be taken first before applying the 'if'. We can assume from your results that 'case/when' has a precedence between &&/|| and and/or:
&&
case/when
or
and
if
So the statement
case
when 1==1 and 2==2: p 'ok'
end
is parsed as
case
(when 1==1) and 2==2: p 'ok'
end
Which is a syntax error. While
case
when 1==1 && 2==2: p 'ok'
end
is parsed correctly as:
case
when (1==1 && 2==2): p 'ok'
end
Which as you note is fine syntax. Since 'if' has the lowest precedence,
if 1==1 and 2==2 then p 'ok' end
is always (whether you use 'and' or &&) parsed as
if (1==1 and 2==2) then p 'ok' end
sample,
if 1==1 and 2==2
p "ok"
end
"ok"
#=> nil
case
when 1==1 and 2==2
p "ok"
end
SyntaxError: compile error
(irb):5: syntax error, unexpected kAND, expecting kTHEN or ':' or '\n' or ';'
when 1==1 and 2==2
^
(irb):7: syntax error, unexpected kEND, expecting $end
from (irb):7
from :0
arggh, i love using case-when and and/or and now both do not work together?? quite a surprise to me there.
kind regards -botp
They work, but you have to accept that you need to play very close attention to precedence when you use them and that parens may be necessary to get what you want.
Alex Gutteridge
Department of Biochemistry
University of Cambridge
···
On 29 Jul 2008, at 08:47, Peña, Botp wrote: