8

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?

3 Answers 3

5

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, and c should 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 = (                   )
Sign up to request clarification or add additional context in comments.

3 Comments

Why is the expression remainder ,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)?
@BorisB. maybe this is misleading. I just wanted to point out that the first assignment is c = 1, followed by b = ... and finally a = ...
@BorisB. actually, this is correct. The whole array is the rvalue, but the elements within the array literal are evaluated from left to right.
4

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] 

5 Comments

Yep just discovered this myself by playing around in the console
What is the reason behind this behaviour, we know that its a = (b = c = 1), 2, 3, even if we are taking more than 3 no. of variables, the behaviour is same!
@RSB sorry I dont get your comment. OP is not doing parallel assignment. He is assigning one object to other. That leaves 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?
@shivam I don't think there is any parallel assignment as there are no multiple comma separated variables. Its simply assigning a the entire array.
@SachinPrasad you're correct. no parallel assignment in the end. I was mistaken at that point. :)
-2

To do what you are talking about you should do as follow:

a,b,c = 1,2,3
    p a #=> 1
    p b #=> 2
    p c #=> 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.