when should one use "and" and "or"

B

botp

Hi All,

just got hit w the ff
case
when x==1 or x==2
print "yeoh!"
end
SyntaxError: compile error
(irb):17: syntax error, unexpected kOR, expecting kTHEN or ':' or '\n' or ';'
when x==1 or x==2
^

"or" and "and" both exhibit the behaviour in ruby1.8/1.9.

workaround
1 put parens around the condition (not again)
2 replace or/and with ||/&&

i believe there are other similar quirks when using "and/or"..
has ruby relegated the use of "and/or"....?

best regards -botp
 
B

botp

#> x =3D 5
#> =A0 =A0=3D=3D>5
#> case x
#> =A0when 2,3
#> =A0 =A0p 'no'
#> =A0when 4,5
#> =A0 =A0p 'yes'
#> end

of course i know that ;-)
im talking about the second type of "case", eg
case
when x.baz and y.foo
....

best regards -botp
 
B

Brian Candler

botp said:
i believe there are other similar quirks when using "and/or"..
has ruby relegated the use of "and/or"....?

No, but it's essentially inherited from perl. These operators have
extremely low precedence, so without parens your statement was being
parsed as something like

(when x==1) or x==2

I think the typical perl use is something like:

open F, "foo" or die "Oops";

If you use || then you need extra params so you don't get
open(F, "foo" || die "Oops");

But if you rely on poetry mode like this it may still trip you up. IMO
you're better off with:

a = (some-expr) || (raise "Oops")
a = (some-expr) || raise("Oops")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top