Block Arguments

Learn how blocks can accept arguments.

Blocks make a lot of sense when passed to methods that are defined on collections like arrays and hashes.

Let’s look at some examples with arrays.

In our previous example that used the times method, our block didn’t accept an argument. A block that accepts an argument looks like this:

Press + to interact
[1, 2, 3, 4, 5].each do |number|
puts "#{number} was passed to the block"
end

Again, this is the same as below:

Press + to interact
[1, 2, 3, 4, 5].each { |number| puts "#{number} was passed to the block" }

Pipes instead of parentheses

Instead of enclosing the block’s argument list with round parentheses, Ruby wants us to use vertical bars. We call them pipes.

For blocks, do |number| is the same as def add_two (number) for a method definition, except that the method wants a name, while a block is anonymous. The |number| and (number) are both argument lists. The first is used for blocks, the second for methods.

Remember: Block arguments are listed between pipes (|) instead of parentheses.

Explanation

Now, when we run the code example above, we’ll see the message printed out for each of the numbers contained in the array.

Again, our code almost reads like an English sentence: naming each of this array’s elements number, output the following message.

The each method is defined on arrays, and it takes each element in the array and calls the block, passing that element as an argument. The block can then do whatever we want it to do with the element. In our case, we interpolate it into a string and print it out to the screen.