Skip to content

Instantly share code, notes, and snippets.

@benburwell
Last active December 16, 2015 03:59
Show Gist options
  • Save benburwell/5374421 to your computer and use it in GitHub Desktop.
Save benburwell/5374421 to your computer and use it in GitHub Desktop.
How to swap variables without the use of a temp variable.
# initial assignment
x = 5
y = 3
# print the values
puts "#{x}, #{y}"
# perform first xor
x = x ^ y
# print new values
puts "#{x}, #{y}"
# perform second xor
y = x ^ y
# print new values
puts "#{x}, #{y}"
# perform third xor
x = x ^ y
# print final (swapped) values
puts "#{x}, #{y}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment