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.

sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    Good answer. And if `x, (y, z), u = 1, *[2, 3]` then `x #=> 1; y #=> 2; z #=> nil; u #=> 3`. – Cary Swoveland Jun 06 '15 at 03:56
  • Ok so splat has precedence over parantheses and the parantheses treat values in them as a single unit – Devashish Bhardwaj Jun 06 '15 at 13:36
  • 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`. – Cary Swoveland Jun 06 '15 at 19:00