Ruby for Programmers – Part 5: Functionality And Blocks

Functions can be defined using “def”:

Functions take variables:

And you can have optional function values:

However, Ruby has a special type of function parameter, the block.

What is a Block?

Blocks are functions you can define at anytime, but are also variables, which are then objects. You can use the ‘lambda’ operator to create blocks as a variable, and use the ‘call’ function to use them:

So having a function as a variable is very useful, as you can define a whole method of stuff before doing things. Note that blocks can come in two different ways, inside angle brackets like the above, or in a “do … end” statement:

And you can use the pipes to denote an argument to this function:

Notice how it raised an error when it didn’t have the right number of arguments?

Functions and Blocks

You can pass a block to a function via two methods, the ampersand or block notation:

Most of the time, we’ll be using the block notation on functions like in the last two examples. The first example uses the reserve word yield, which runs the included block. If you notice, the block isn’t an argument in the function, so you can use “block_given?” to tell if the block exists:

As we’ll show in the next section on Array, blocks are very useful.