Brackets in block variables

Considering

a = [[:a, :b, :c]]

1) I understand that

a.each{|(x, y), z| p z} # => :b

that there are two variables (x, y)and z, therefore, the third element is :cdiscarded, but zcorresponds :b. And I understand that

a.each{|(x, y), z| p y} # => nil

which (x, y)matches :a, and since it is not an array, there are no elements for it, so it ymatches nil.

But how

a.each{|(x, y), z| p x} # => :a

work? I expect to nilbe returned.

2) Why are return values ​​such?

a.each{|(x, y)| p x} #=> :a
a.each{|(x, y)| p y} #=> :b

I expect both of them to return nil.

+5
source share
1 answer

This is because of the parallel assignment syntax .

a = [[:a, :b, :c]]

, a.each , [: a,: b,: c].

:

(x, y), z = [:a, :b, :c]
#=> x == :a, y == nil, z == :b

(x, y) - , : a x , z : b.

:

(x, y) = [:a, :b, :c]
#=> x == :a, y == :b

(x, y) [: a,: b,: c], x, y : a : b .

, args + optional args (keyword args) + rest args, . "", .

:

(a,b) = 1,2
=> [1, 2] # array match
#=> a == 1, b == 2

(a,b)=[1,2]
=> [1, 2] # array match
#=> a == 1, b == 2

, .

+9

All Articles