Ruby has quite a lot of “exotic” features that are not used that often, but when you need to utilize some metaprogramming magic, you can easily take advantage of them. One of such features is Object.instance_exec which you might be familiar with if you’ve ever built some more advanced DSL.
The great thing about
Object#instance_exec is that it allows to execute code within the context of a given object but it also gives possibility to pass arguments from the current context. Thanks to that, we can build some nice DSLs and other features like this:
1 2 3
An interesting thing is that there is a class equivalent of
Object#instance_exec – Module.class_exec. It would be easy to figure out some theoretical example how it can be used but what could be the real-world use case where this is the best approach to solve the problem?