< All Blog

Ruby: Swap Variables in Oneline

November 15, 2022

In Ruby, there is a way to swap values of two different variables without using temporary variables.

Let's say there are two variables that we'd like to swap.

a = 100
b = 200

The naive way to implement swap(x, y) is using tmp variable to store either of variable values temporary.

tmp = a
a = b
b = tmp

But if you use Ruby's parallel assignments, the above code can be written as follows:

a, b = b, a

Recommended Posts

  1. Ruby: Array Brackets Operator Edge Cases

    November 14, 2022
    In Ruby, there is a [] (brackets) operator to access items in Array. https://ruby-doc.org/core-3.1.2/Array.html#method-i-5B-5D You can pass [start, length] to …