[前][次][番号順一覧][スレッド一覧]

ruby-changes:26820

From: drbrain <ko1@a...>
Date: Fri, 18 Jan 2013 14:15:56 +0900 (JST)
Subject: [ruby-changes:26820] drbrain:r38872 (trunk): * doc/syntax/methods.rdoc: Added Array Decomposition.

drbrain	2013-01-18 14:15:44 +0900 (Fri, 18 Jan 2013)

  New Revision: 38872

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=38872

  Log:
    * doc/syntax/methods.rdoc:  Added Array Decomposition.

  Modified files:
    trunk/ChangeLog
    trunk/doc/syntax/methods.rdoc

Index: doc/syntax/methods.rdoc
===================================================================
--- doc/syntax/methods.rdoc	(revision 38871)
+++ doc/syntax/methods.rdoc	(revision 38872)
@@ -237,6 +237,67 @@ This will raise a SyntaxError: https://github.com/ruby/ruby/blob/trunk/doc/syntax/methods.rdoc#L237
     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 <code>*</code> 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 <code>*</code> causes any remaining arguments to be
Index: ChangeLog
===================================================================
--- ChangeLog	(revision 38871)
+++ ChangeLog	(revision 38872)
@@ -1,3 +1,7 @@ https://github.com/ruby/ruby/blob/trunk/ChangeLog#L1
+Fri Jan 18 14:11:01 2013  Eric Hodel  <drbrain@s...>
+
+	* doc/syntax/methods.rdoc:  Added Array Decomposition.
+
 Fri Jan 18 12:54:21 2013  Nobuyoshi Nakada  <nobu@r...>
 
 	* tool/rbinstall.rb (gem): Gem.ensure_gem_subdirectories makes

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]