Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR-ing two objects

Tags:

ruby

I have to XOR two objects and thought I could use Ruby's built-in XOR operator (^) but it doesn't work. I wanted to use it to test that exactly one of my objects was initialized.

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

Interestingly, I can do

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

I think it's odd that Ruby doesn't allow you to XOR two objects innately. Is there another command I'm missing or was this functionality just not built?

Obviously a solution to my problem is to just do the following:

(a || b) && !(a && b) 
like image 715
AlexQueue Avatar asked Aug 25 '26 06:08

AlexQueue


1 Answers

How about this?

a = Object.new
b = Object.new
c = nil
!a ^ !b # => false
!a ^ !c # => true
like image 64
Jeff Peterson Avatar answered Aug 28 '26 02:08

Jeff Peterson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!