Skip to content

Instantly share code, notes, and snippets.

@luisalima
Created April 30, 2016 18:08
Show Gist options
  • Save luisalima/bfe722aa031d2ac05fb124b2c599ce6f to your computer and use it in GitHub Desktop.
Save luisalima/bfe722aa031d2ac05fb124b2c599ce6f to your computer and use it in GitHub Desktop.
Bit manipulation in Ruby
# swapping two integers, without using a temporary variable
a = 5 # 5
b = 7 # 7
a.to_s(2) # "101"
b.to_s(2) # "111"
a ^= b # a is now "010"
b ^= a # b is now "101"
a ^= b # a is now "111"
@emcoding
Copy link

I stumbled upon this. In Ruby you can also do:

a, b = b, a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment