Keyword for exclusive or in ruby?

后端 未结 7 1930
广开言路
广开言路 2021-01-04 00:03

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?

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 00:55

    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
    

提交回复
热议问题