Yielding


#1



Okay, so this isn't about one lesson in particular. I'm just having a hard time grasping what the "yield" keyword does exactly. Could some one please ELI5...


Replace this line with your code.


#2

When a call to a function includes a block, the block is a parameter as well so the function can see it. yield tells the function to insert the output of the block, then continue.

def my_function(name)
    yield name
end

my_function("Roy") { |name| puts "My name is #{name}." }

Output

My name is Roy.

Notice that the code inside the block is what ran inside the function. The function could (probably would) have more code exclusive to it, but I left that out so we can see how it segues to the passed in block.


#3

You can see how it works here: http://www.pythontutor.com, just select Ruby and paste the code in.