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:
- “Ronda” is passed in new_name as an argument
- We now run into the yield keyword, which stops the code from executing
- Yield gives control to the new block, where “Ronda” is passed into the parameter of the new block as |name|
- Control is given back to the original block and the method closes
EDIT: WHY ON EARTH would one want to do this? This is a feature of the language, so it must have a use and usefulness…www.codecademy.com