Hey Codecademy,
I am starting off on this new unit, and right off the bat yielding threw me off. I have no idea what it means or why use it? Can someone help me out with this? Maybe, explain what yielding means and why would it be used, so that a layman mortal like myself could understand it?
Than you very much for all of your help.
B.G. :grin:


This tutorial does a good job of demonstrating yield:

Ruby Primer - 0.1 Yield

In lesson 3 we are given this code to examine:

def block_test
  puts "We're in the method!"
  puts "Yielding to the block..."
  puts "We're back in the method!"

block_test { puts ">>> We're in the block!" }

When we run it, notice what prints in the third line?

We're in the method!
Yielding to the block...
>>> We're in the block!
We're back in the method!

The function has no parameter. The interpreter knows to execute the caller block whenever it encounters yield in the function code. That's the basic mechanics.

In lesson 4 we see this applied when there is a parameter. That gets passed into the function so becomes a local variable. It can be passed to the block with the yield and so behaves like any function parameter.


I was confused by this lesson as well. I found this video explanation on Ruby yield to be really clear and insightful: https://www.youtube.com/watch?v=ObR8UuaPc6Q


Thanks.... :grin:.. I really appreciate it!