summaryrefslogtreecommitdiff
path: root/doc/syntax
diff options
context:
space:
mode:
authordrbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-01-15 02:49:54 +0000
committerdrbrain <drbrain@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-01-15 02:49:54 +0000
commit108f3acbe41ec2de5164109ee80377fe31951e08 (patch)
treeeb8ae49bf87b1f9281c70953a30d3b8545687451 /doc/syntax
parentec2bdfc7635e98a7f694cc8f67d5b4a0d8fc83bc (diff)
* doc/syntax/methods.rdoc (Block Argument): Added section on block
argument. Thanks to Andy Lindeman. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38824 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'doc/syntax')
-rw-r--r--doc/syntax/methods.rdoc32
1 files changed, 32 insertions, 0 deletions
diff --git a/doc/syntax/methods.rdoc b/doc/syntax/methods.rdoc
index 70a9163..a86576c 100644
--- a/doc/syntax/methods.rdoc
+++ b/doc/syntax/methods.rdoc
@@ -210,6 +210,38 @@ is raised.
When mixing keyword arguments and positional arguments, all positional
arguments must appear before any keyword arguments.
+== Block Argument
+
+The block argument is indicated by <code>&</code> and must come last:
+
+ def my_method(&my_block)
+ my_method.call(self)
+ end
+
+Most frequently the block argument is used to pass a block to another method:
+
+ def each_item(&block)
+ @items.each(&block)
+ end
+
+If you are only going to call the block and will not otherwise manipulate it
+or send it to another method using <code>yield</code> without an explicit
+block parameter is preferred. This method is equivalent to the first method
+in this section:
+
+ def my_method
+ yield self
+ end
+
+There is also a performance benefit to using yield over a calling a block
+parameter. When a block argument is assigned to a variable a Proc object is
+created which holds the block. When using yield this Proc object is not
+created.
+
+If you only need to use the block sometimes you can use Proc.new to create a
+proc from the block that was passed to your method. See Proc.new for further
+details.
+
== Exception Handling
Methods have an implied exception handling block so you do not need to use