Inversion of Control
Explore the principle of inversion of control in Ruby.
We'll cover the following
There are many more methods that accept blocks in Ruby, and they do very different things. However, they have one thing in common: a method that accepts a block from us can pass control to us.
This design is an example of the principle of inversion of control, and it’s the real reason why Rubyists love blocks so much.
What does that mean?
In short, it means that Matz, Ruby’s creator, put a tool in place that can be used to allow methods to pass control to its users (the programmer).
Note: Control in this context refers to the question of who gets to decide how things work.
In older languages, where there was no such tool, people either had to implement many very specific methods and guess what users might need in the future, or they’d decide to simply not implement any of these methods at all.
For example, in Ruby, we don’t have to define lots of methods like select_odd
, select_even
, select_lesser_than
, select_greater_than
and so on, where each of these methods would only be useful for one very specific use case.
Instead, the Array
class only has to implement one single, very generic method for arrays: select
. Because Ruby uses blocks, the method can allow programmers to specify the criterion themselves by passing a piece of code, in the form of a block, to the method.
That way, Ruby lets us take control and specify what’s used as element selection criterion.
We mention this here because it’s a nice example of a rather abstract principle applied to software design. There are many other principles like these, and they’ll make more and more sense over time. Programming languages and code, from this perspective, are subjects of design, and therefore art, as well as a subject of social and cultural questions rather more than strictly logical or technical ones.