Parallel assignment in Ruby facilitates the initialization of variables using a single line of code. The variables to be initialized precede the =
operator and are separated by commas. This =
operator is then followed by the values to be assigned to the primary variables. As the name suggests, all the assignments are parallel. The assignments are done according to the order of variables on the left.
Consider the generic syntax below:
var1, var2, var3 = val1 , val2, val3
The three variables on the left, var1
, var2
, and var3
, were assigned val1
, val2
, and val3
, respectively. The values on the right can be of any data type.
We have five use cases that showcase various forms of parallel assignment.
Note: Here, we referred variables to vars and values to vals.
Let’s discuss them in detail.
var1, var2, var3, var4 = "educative" , "provides", "interactive", "learning"puts var1, var2, var3, var4
var1
, var2
, var3
, and var4
and assigned them string
values of "educative"
, "provides"
, "interactive"
, and "learning"
.Note: Using an array of values on the right is also acceptable per ruby syntax. Wrap the above values on the right side of
=
by[]
and witness this yourself!
Nil
value.var1, var2, var3, var4 = "educative" , "provides", "interactive"puts var1, var2, var3 # read variables that got their values assignedputs var4.nil? # is var4 Nil?
var1
, var2
, var3
, and var4
and assigned them string
values of "educative"
, "provides"
, and "interactive"
leaving the fourth variable with no value.var4
is Nil
or not.var1, var2, var3 = "educative" , "provides", "interactive", "learning"puts var1, var2, var3
var1
, var2
, and var3
and assigned them string
values of "educative"
, "provides"
, "interactive"
, and "learning"
.Consider an array of int
. We can destructure it using *
and assign its values to other variables in the parallel assignment as follows:
var3 = 2,3,4,5,6,7a, b, c, d, e = 1, *var3puts a, b, c, d, e
var3
and assigned int
values of 1
, 2
, 3
, 4
, 5
, 6
, and 7
.*
to destructure the array.Free Resources