Ruby blocks + Yield

Today I was doing some Ruby and reading blocks. Along came Yield… WTF???? Did some research then…

Ruby Code blocks are definitely one of the coolest features of Ruby and are chunks of code between braces or between do- end that you can associate with method invocations, almost as if they were parameters.

In ruby, methods may receive code block.

A Ruby block is a way of grouping statements, and may appear only in the source adjacent to a method call; the block is written starting on the same line as the method call’s last parameter (or the closing parenthesis of the parameter list).

The code in the block is not executed at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method.

The Ruby standard is to use braces for single-line blocks and do- end for multi-line blocks. When a method expects a block, it invokes it by calling the yield function.
Let’s look at an example of the yield statement:
Continue reading

Advertisements