Can someone explain this behavior:
a = b = c = 1, 2, 3
a # => [1, 2, 3]
b # => 1
c # => 1
In the assignment a = b = c = 1, 2, 3, the variables a, b, and c should be assigned [1, 2, 3]. Any idea?
Can someone explain why is this happening
@shivam already answered the question, but adding some parentheses might clarify things even more.
a = b = c = 1, 2, 3
is interpreted as:
a = [(b = (c = 1)), 2, 3]
The expression is evaluated in this order:
c = 1
b = ( )
a = [( ), 2, 3]
the variables
a,b, andcshould be assigned[1, 2, 3]
To get the expected result, you could write:
a = b = c = [1, 2, 3]
which is interpreted as:
a = (b = (c = [1, 2, 3]))
and evaluated in this order:
c = [1, 2, 3]
b = ( )
a = ( )
,2,3 left until evaluating a, and not before, when evaluating c, or even b (although that would make even less sense)? I fail to see the logic behind it. Don't normal languages evaluate the rvalue first and then assign it to the lvalue(s)?c = 1, followed by b = ... and finally a = ...You are being confused
a=b=c=1,2,3
is actually:
a = (b = c = 1), 2, 3
that leaves
c = 1 # => 1
b = c # => 1
a = 1,2,3 # => [1, 2, 3]
a = (b = c = 1), 2, 3, even if we are taking more than 3 no. of variables, the behaviour is same!b with same object as c but the same object cannot be assigned to a as OP has given 2,3 after the assignment (which btw is parallel assignment). I guess my expansion clearly explain that?