Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyword for exclusive or in ruby?

Tags:

ruby

boolean

xor

Does Ruby have a plain-English keyword for exclusive or, like they have "and" and "or"? If not, is this because exclusive or doesn't allow evaluation short-cutting?

like image 272
Andrew Grimm Avatar asked Feb 25 '09 08:02

Andrew Grimm


4 Answers

No it doesn't, you can only use ^.

Don't know why there isn't particularly, may just be because it isn't as commonly used.

like image 67
Garry Shutler Avatar answered Oct 19 '22 10:10

Garry Shutler


I ran into an issue because the '^' operator acts bitwise on numbers,

true ^ 1
=> false

1 ^ true
TypeError: can't convert true into Integer
true ^ 1

so my workaround was:

( !!a ^ !!b ) where the double-bang coerces them into booleans.

!!1 ^ !!true
=> false

!!1 ^ !!false
=> true
like image 34
Matt Van Horn Avatar answered Oct 19 '22 10:10

Matt Van Horn


Firstly, I don't think shortcircuiting can sensibly apply to XOR: whatever the value of the first operand, the second needs to be examined.

Secondly, and, &&, or and || use shortcircuiting in all cases; the only difference between the "word" and "symbol" versions is precedence. I believe that and and or are present to provide the same function as perl has in lines like

process_without_error or die

I think the reason for not having a xor named function is probably that there's no point in a low-precedence operator in this case and that it's already a confusing enough situation!

like image 44
Mike Woodhouse Avatar answered Oct 19 '22 10:10

Mike Woodhouse


Try ^

true  ^ false #=> true
true  ^ true  #=> false
false ^ false #=> false

No plain english equivalent operator though.

like image 13
Alex Wayne Avatar answered Oct 19 '22 10:10

Alex Wayne