Learn Ruby
Array
14.13
Lesson

Destructuring

Usually we assign values from an array like this.

Rather than taking four separate statements to assign values the same thing can be done in one line as shown below.

Let’s see one more example.

Adding a star before a variable name makes that variable greedy and that variable takes up all the values.

In the above case variable b takes up both the values 2 & 3 and puts it in an array.

Splat is greedy but Ruby is smart

In the above case even though b is greedy Ruby first attempts to assign at least one value to each of the variables. In this case one value is assigned to a, b & c. Since nothing else is left then b ends with only 2 but since b is using a splat operators that 2 is an array.

Now let’s try the same thing with more values.

In the above case ruby first assigned 1 to a and 2 to b and 5 to c. Still we are left with 3 & 4 which were assigned to b.

Two greedy variables will cause problems

In the above case both b and c are trying to be greedy. It’s not possible to have two greedy variables so Ruby fails with an error.

nil when there are not enough elements

If there are not enough values for variables then the variables who did not get any value are assigned nil value by Ruby.

Empty array for splat operators

If a variable is using splat then it always get an array. If there is no value for the splat variable then the final result is an empty array.