# Swapping variables using Ruby

Swapping 2 numbers is the often asked interview question to see how many ways you know to swap and also to check your technical depth in the core area. There would be lot of technics like using temp variable, using XOR operator and if it was just numbers using addition and subtraction would do the need.

But in ruby I found this interesting piece called parallel assignment to swap 2 numbers, not only to swap but also to shift the values of variables. Let me show you an example,

No temp, no XOR just swapping. Let me show you another example,

In parallel assignment, values in the right hand side acts as arrays and each and every value is assigned to the variable in the LHS. So it means we can use arrays as RHS in PA and the values which don t have corresponding variables will be left out and variables which don t have corresponding values will be nil.

Using splat operator we can capture the rest of values to be an array.

And for the sake of preserving other techniques here,

Temp Variable :

Xor :

Using basic math :