Explain yield please


#1

Will someone please briefly explain how does yield actually work ? and what is it ? and how to use it?


#2

def foo
    puts "Foo"
    yield
end

foo { puts "Bar" }

Output

Foo
Bar

The above runs immediately without a method call. Notice that the method name and the block are the same. This is important.

yield is essentially a place holder for the chunk of code in the block. Say for instance you have a piece of code that repeats inside the method. Written as a block of the same name, it can be recalled any number of times.

def foo
    # some code
    yield
    # some more code
    yield
    # more code
    yield
end
foo { # code }

The block is called three times in the above.

@Alex J explains it very well, so I defer to his response:

https://www.codecademy.com/en/forum_questions/51c72e759c4e9d410501df42


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.