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
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
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:
b, a
, creates a temporary array with the values of b
and a
.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à!
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©