Tuesday, March 27, 2007

How do you swap variables?

At least some 10 years ago someone asked me this question in an interview - "How do you swap two variables without using a temporary variable"
I now vaguely remember how I answered the question then but I know I did *not* use XOR in that answer, I did not know it at that time but its really very cool.


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


But of course in Ruby you would just do


a,b = b,a

and thats it! Have a nice day. May I help the next customer in line?

This is Ruby parallel assignment in action which has several cool uses but begins to really shine when you splat and unsplat.

No comments: