Yield Block


Collapse Content

Here is a simple method that doesn't do much:

def take_block
    puts "before block"
    puts "after block"
end

take_block

The last line calls the method take_block which prints the following output:

before block
after block

Pretty boring. But we'll see how it can get more interesting.

blocks

You know that you can pass variables (such as 3 or "hello") to other methods, but Ruby also lets you pass around pieces of code! The common way to do those is with a block,* a piece of code marked with do and the beginning and end at the end.

This code below calls take_block again, but passes it a block of code:

#method that takes block
def take_block
    puts "before block"
    yield
    puts "after block"
end

# call method and pass it a block
take_block do
    puts "i am block"   
end 

This will print out the following:

before block
i am block
after block

Notice how the method take_block now has a line that says yield. This calls the block that was passed into the method. Ruby on Rails uses a similar structure to create web pages. A general layout page stores the content shown on every page, and it calls yield to run the code of a specific page. See the challenge below for a simplified version of this.

Blocks can be surrounded with curly braces {} instead of do and end:

take_block { puts "i am block" } 

This is usually used when the block's code fits on one line.

*A block is similar to lambdas found in other languages.

Challenge

The code below passed a block to a template function that still needs to be written. Create a function below called template that prints the word "start", then yields a block passed to it, and then prints the word "end".

(Don't print any newlines.)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Contact Us