Parallel assignment

356 views

In Ruby, what is the idiomatic way to swap the values of two variables in a single line?

The correct answer is

a, b = b, a

temp = a; a = b; b = temp

a.swap(b)

a ^ b ^ a

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

In Ruby, the assignment statement allows you to simultaneously assign values to multiple variables.

The expression a, b = b, a takes advantage of this feature to swap the values of variables a and b in a single line.

Here's how it works:

  1. The right-hand side, b, a, creates a temporary array with the values of b and a.
  2. The left-hand side, a, b, then destructively assigns these values back to a and b, effectively swapping their values.

This approach is concise, readable, and considered idiomatic in Ruby for swapping variable values.

It eliminates the need for a temporary variable and is a common and elegant pattern in the language.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©