Parallel assignment with parentheses and splat operator
Asked Answered
B

1

5

I got this:

x,(y,z)=1,*[2,3]

x # => 1
y # => 2
z # => nil

I want to know why z has the value nil.

Bodycheck answered 6/6, 2015 at 3:43 Comment(0)
P
9
x, (y, z) = 1, *[2, 3]

The splat * on the right side is expanded inline, so it's equivalent to:

x, (y, z) = 1, 2, 3

The parenthesized list on the left side is treated as nested assignment, so it's equivalent to:

x = 1
y, z = 2

3 is discarded, while z gets assigned to nil.

Perdita answered 6/6, 2015 at 3:52 Comment(3)
Good answer. And if x, (y, z), u = 1, *[2, 3] then x #=> 1; y #=> 2; z #=> nil; u #=> 3.Bin
Ok so splat has precedence over parantheses and the parantheses treat values in them as a single unitBodycheck
I don't think precedence is relevant here, as the parenthesis and splat are on opposite sides of the equality. The key is Yu's statement, "The splat * on the right side...". Parallel assignment causes x to be set equal to 1, (y,z) set equal to 2 and so on, and if (y,z) = 2, then y #=> 2; z #=> nil.Bin

© 2022 - 2024 — McMap. All rights reserved.