Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested assignment in ruby

Tags:

ruby

nested

Why do these assignment happen?

a,(b,c),d = 1,2,3,4 # a=1, b=2,c=nil, d=3

why is d=3 and c=nil?

yet on this

a,(b,c),d = 1,[2,3],4 # a=1, b=2,c=3, d=4 

c=3 and d=4?

this is ok since its 2 arugments vs 3 values

a,(b,c),d = 1,[2,3,4],5 # a=1, b=2,c=3, d=5 

and this seems logical, since its with a splat

a,(b,*c),d = 1,[2,3,4],5 # a=1, b=2,c=[3,4],d=5 
like image 524
Nick Ginanto Avatar asked Mar 23 '23 06:03

Nick Ginanto


1 Answers

Very good explanation in the book : The Ruby Programming Language

4.5.5.6. Parentheses in parallel assignment

One of the least-understood features of parallel assignment is that the lefthand side can use parentheses for “subassignment.” If a group of two or more lvalues is enclosed in parentheses, then it is initially treated as a single lvalue. Once the corresponding rvalue has been determined, the rules of parallel assignment are applied recursively—that rvalue is assigned to the group of lvalues that was in parentheses. Consider the following assignment:

x,(y,z) = a, b

This is effectively two assignments executed at the same time:

x = a
y,z = b

But note that the second assignment is itself a parallel assignment. Because we used parentheses on the lefthand side, a recursive parallel assignment is performed. In order for it to work, b must be a splattable object such as an array or enumerator.

Here are some concrete examples that should make this clearer. Note that parentheses on the left act to “unpack” one level of nested array on the right:

x,y,z = 1,[2,3]             # No parens: x=1;y=[2,3];z=nil
x,(y,z) = 1,[2,3]           # Parens: x=1;y=2;z=3

a,b,c,d = [1,[2,[3,4]]]     # No parens: a=1;b=[2,[3,4]];c=d=nil
a,(b,(c,d)) = [1,[2,[3,4]]] # Parens: a=1;b=2;c=3;d=4

Now coming to your first confusion :

a,(b,c),d = 1,2,3,4 # a=1, b=2,c=nil, d=3

why is d=3 and c=nil?

This is because a,(b,c),d = 1,2,3,4 is actually as below :

a = 1
(b,c) = 2
d = 3

Second confusion :

a,(b,c),d = 1,[2,3],4 # a=1, b=2,c=3, d=4

c=3 and d=4?

This is because a,(b,c),d = 1,[2,3],4 is actually as below :

a = 1
(b,c) = [2,3]
d = 4
like image 119
Arup Rakshit Avatar answered Mar 24 '23 19:03

Arup Rakshit