XOR -induce two objects

I have XOR two objects and I thought I could use Ruby's built-in XOR operator ( ^

) but it doesn't work. I wanted to use it to check that only one of my objects was initialized.

a = Object.new
b = Object.new
a ^ b # => NoMethodError: undefined method `^' for #<Object:0x007...>

      

I wonder what I can do

a = nil
b = Object.new
a ^ b # => true

      

It seems strange to me that Ruby doesn't allow you to XOR two objects inherently. Is there another command I'm missing or is this function just not built?

Obviously, the solution to my problem is this:

(a || b) && !(a && b) 

      

+3


source to share


3 answers


How about this?



a = Object.new
b = Object.new
c = nil
!a ^ !b # => false
!a ^ !c # => true

      

+4


source


I wonder what I can do

a = nil
b = Object.new
a ^ b # => true

      

This is because it NilClass

has a method nil ^ obj

.



Is there another command I'm missing or is this function just not built?

It was not built.

0


source


You need to override the operator ^

(actually the method) for your objects. Something like:

class YourObject
  def ^(rhs)
    # You may want to do a check here that 
    #   rhs is of the same type as your object,
    #   and throw an error if not
   (self || rhs) && !(self && rhs)
  end
end

      

I recommend that you replace your own class and not modify Object.

0


source







All Articles