1 min read

XOR Magic Trick

Swapping values with no intermediate variable
XOR Magic Trick
Photo by Praveen kumar Mathivanan / Unsplash

The eXclusive-OR operator, normally the ^ operator in most programming languages can be used to swap the values of two variables without an intermediate variable:

x ^= y
y ^= x
x ^= y

Let's take a look at this in Ruby. Pick a number, any number:

x = 27
y = 94

x ^= y
# => 69

y ^= x
# => 27

x ^= y
# => 94

puts 'TaaaDaaa'

Fun, yes; useful, probably nope.