Ruby, Tech

Ruby Blocks

In this article we will discuss how default arguments work and analyze a situation where they can be useful.

The Ruby block

Ruby blocks are code that can be run by other code. All methods can accept blocks, but it’s up to them whether they do something with them or not.

Blocks can take parameters

Ruby blocks accept parameters and can also initialize them with default values.

In the example above, we initialize the local block variable greeting with the value “hi”.

The behavior can be demonstrated more easily if we use procs:

Usefulness

For a real example let’s consider the shared examples feature from RSpec, the well know gem for behavior driven development inside the Ruby ecosystem. So, when we use shared_examples we can define a default value and thus avoid code duplication.

Conclusion

To sum up, Ruby allows blocks to receive parameters and enables its initialization with default values. This is applicable is some real world scenarios, such as DRYing up our RSpec suite.