Actions
Misc #15514
openAdd documentation for implicit array decomposition
Status:
Open
Priority:
Normal
Assignee:

Description
The documentation for Array Decomposition says: "[...] you can decompose an Array during assignment using parenthesis [sic]" and gives an example:
(a, b) = [1, 2]
p a: a, b: b # prints {:a=>1, :b=>2}
But – as we all know – it's also possible without parentheses, i.e.
a, b = [1, 2]
p a: a , b: b #=> {:a=>1, :b=>2}
This also applies to block arguments when yielding multiple values vs. yielding a single array:
def foo
yield 1, 2
end
def bar
yield [1, 2]
end
foo { a, b p a: a, b: b }
#=> {:a=>1, :b=>2}
bar { a, b p a: a, b: b }
#=> {:a=>1, :b=>2}
In both cases, parentheses are optional.
This implicit array decomposition could be quite surprising for newcomers. The documentation should cover it.
Updated by shevegen (Robert A. Heiler) over 4 years ago
Agreed.
Updated by lugray (Lisa Ugray) over 4 years ago
If that's covered (and I agree it should be) it's also worth showing a case where they are not optional:
def baz
yield [1, 2], 3
end
baz { a, b, c p a: a, b: b, c: c }
#=> {:a=>[1, 2], :b=>3, :c=>nil}
baz { (a, b), c p a: a, b: b, c: c }
#=> {:a=>1, :b=>2, :c=>3}
Actions
Like0
Like0Like0