Ruby Sparkle: How to swap two numbers

Here's a perennial question how do you swap two numbers effectively ? Let's say a=5 and b=3 and you want to swap a and b so that a now holds 3 and b = 5.
So in the typical C way, common answer is use a temporary variable for swapping

temp = a
a = b
b = temp

Now for the stingy ones who don't wanna waste memory, here's another way

a = a + b;

b = a - b;
a = a - b;

If you are wondering what the hell have I been smoking, cover your eyes to keep you from being blinded by the brilliance of Ruby

a, b = b, a

This is like a gloved slap in the face. Touche !

No comments:

Post a Comment