Wednesday, May 30, 2012

Swapping Variables



So ruby offers this great feature I didn't know about (and I have been programming in ruby 'professionally' for past ~4 months) called Parallel Assignment. Which is to say that you can assign multiple variable different values at the same time effectively.

'Cool Story Bro,' you might say. Why is that a noteworthy thing? Because this just allows me to my assignments in one line of code? I could do that in C++/Java too with semi-colons in between the assignments! No sir, that's not the power of it.
The power is that first the values are read from the right side (in the order that they are written) and when all of them are read, then are written to the variables on the left.
Consider the famous swapping variables exercise which is done typically as:
temp = a;
a = b;
b = temp;
Using Parallel Assignment, you can do this as:
a, b = b, a
Well, if it ain't been long since you did this (or made someone do this), you will enjoy this nifty little trick.

That's all for now :)