Yielding to Blocks
As you use blocks, you will discover that the most common usage involves passing exactly one block to a method. This pattern is extremely popular in the Ruby world, and you'll find yourself using it all the time.
Ruby has a special keyword and syntax to make this pattern easier to use, and yes, faster! Meet the
yield keyword, Ruby's implementation of the most common way of using blocks.
Here's an example that uses regular block syntax.
As you can see, the
calculation method accepts two numbers and a block that can perform a mathematical operation.
Let's now do this using
As you can see, the results are identical. Feel free to play around with the example to get a better feel for the new syntax.
Let me call out how the example using
yield is different from the regular approach.
- The block is now no longer a parameter to the method. The block has been implicitly passed to the method - note how it's outside the parentheses.
- Yield makes executing the block feel like a method invocation within the method invocation rather than a block that's being explicitly called using
- You have no handle to the block object anymore - yield "magically" invokes it without any object references being involved.
Note that blocks can be passed implicitly to methods without any parameters. The syntax remains the same.
Here's an example where neither the method nor the block take any parameters.