Blocks, Procs and Lambda


yield is a special thing in ruby. Using yield a method can ask block to be executed.

Here the method first prints “Good morning”. Then the method yields the control to the block. Once block is processed then the method gets the control back and then the method prints “Good evening”.

If the method does not get a block to execute then method will raise an error. Let’s try it out and this time no block will be passed to the method.

You should get an error in the case given below:

We want to “yield” to block only if a block is passed. There is no point in yielding to a block if there is no block. We can solve this by using method block_given?. block_given? would return true if a block is passed.

If a block is passed then that block will be evaluated.