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?
Any implementation of xor
won't allow short circuiting. Both expressions need to be evaluated no matter what.
Ruby does provide the ^
operator, but this will choke on truthy values. I've implemented a function to handle the cases where I want an xor
that behaves more like and
and or
:
def xor(a,b)
(a and (not b)) or ((not a) and b)
end
Unlike ^
, this function can be used in situations similar to the following:
xor("hello".match(/llo/), false) # => true
xor(nil, 1239) # => true
xor("cupcake", false) # => false