Yielding Under The Hood

The yield keyword allows us to pass in a set of additional instructions during a method invocation, via a block.

Think of the yield keyword as if it was a yield traffic sign:

  • Driving: if you are driving down the road and see a yield sign, you pause to let other vehicles pass before you re-enter the road
  • Ruby: when Ruby see’s the yield keyword, its stops running the current code block and allows a new code block to pass through, it then returns control back to the initial block

Ruby does this for under the hood and uses yield to help us do things like iterate through an object and pass (yield) it a block of code.

In the example below, we see how the yield keyword is being executed under the hood.

The yield_name method takes an parameter, new_name and prints out a string. We use the yield keyword to pass in a new block when we initialize.

How this method works:

  1. “Ronda” is passed in new_name as an argument
  2. We now run into the yield keyword, which stops the code from executing
  3. Yield gives control to the new block, where “Ronda” is passed into the parameter of the new block as |name|
  4. Control is given back to the original block and the method closes

References:

www.learn.co