From 1d5a5c235fe2af8cda21ca8224a139391dc4c211 Mon Sep 17 00:00:00 2001 From: drbrain Date: Fri, 18 Jan 2013 05:15:44 +0000 Subject: [PATCH] * doc/syntax/methods.rdoc: Added Array Decomposition. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38872 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 4 +++ doc/syntax/methods.rdoc | 61 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/ChangeLog b/ChangeLog index 785a97a401..053e0c5810 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +Fri Jan 18 14:11:01 2013 Eric Hodel + + * doc/syntax/methods.rdoc: Added Array Decomposition. + Fri Jan 18 12:54:21 2013 Nobuyoshi Nakada * tool/rbinstall.rb (gem): Gem.ensure_gem_subdirectories makes diff --git a/doc/syntax/methods.rdoc b/doc/syntax/methods.rdoc index d5d0ea402d..5499632f76 100644 --- a/doc/syntax/methods.rdoc +++ b/doc/syntax/methods.rdoc @@ -237,6 +237,67 @@ This will raise a SyntaxError: a + b + c end +=== Array Decomposition + +You can decompose (unpack or extract values from) an Array using extra +parentheses in the arguments: + + def my_method((a, b)) + p a: a, b: b + end + + my_method([1, 2]) + +This prints: + + {:a=>1, :b=>2} + +If the argument has extra elements in the Array they will be ignored: + + def my_method((a, b)) + p a: a, b: b + end + + my_method([1, 2, 3]) + +This has the same output as above. + +You can use a * to collect the remaining arguments. This splits +an Array into a first element and the rest: + + def my_method((a, *b)) + p a: a, b: b + end + + my_method([1, 2, 3]) + +This prints: + + {:a=>1, :b=>[2, 3]} + +The argument will be decomposed if it responds to #to_ary. You should only +define #to_ary if you can use your object in place of an Array. + +Use of the inner parentheses only uses one of the sent arguments. If the +argument is not an Array it will be assigned to the first argument in the +decomposition and the remaining arguments in the decomposition will be +nil+: + + def my_method(a, (b, c), d) + p a: a, b: b, c: c, d: d + end + + my_method(1, 2, 3) + +This prints: + + {:a=>1, :b=>2, :c=>nil, :d=>3} + +You can nest decomposition arbitrarily: + + def my_method(((a, b), c)) + # ... + end + === Array/Hash Argument Prefixing an argument with * causes any remaining arguments to be