* 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
This commit is contained in:
drbrain 2013-01-15 02:49:54 +00:00
parent ec2bdfc763
commit 108f3acbe4
2 changed files with 37 additions and 0 deletions

View File

@ -1,3 +1,8 @@
Tue Jan 15 11:49:31 2013 Eric Hodel <drbrain@segment7.net>
* doc/syntax/methods.rdoc (Block Argument): Added section on block
argument. Thanks to Andy Lindeman.
Tue Jan 15 10:54:59 2013 Eric Hodel <drbrain@segment7.net>
* doc/syntax/calling_methods.rdoc (Arguments): Added improved

View File

@ -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