Refinements in ruby


Today I had the opportunity to use for the first time in my almost 8 years of Ruby programming.
So in general it works in the way that you can override some classes in Ruby but the change is not globally.
It creates the module, applies monkey patching, and using ModuleName. That makes things overridden only in the context of
the runtime of that using.

Let's describe it with my use case example. In application, we had an evaluator for formulas. Implementation details are not important, what we should focus on is that after parsing data we had a simple eval like that:
max( nil * 10, 20 )

Normally any operation like * on a nil object raises an error and that was ok. But in this case, we have a proper value of 20 which should be the result of that code since it is the maximum value from passed values.

So my solution is to expand basic arithmetic methods in NilClass, and thanks to using refinement i did it only in the context of our evaluator without causing any changes in the rest of application.

  class Evaluator
    Refinement = do
      refine NilClass do
        %i[- + / *].each do |operator|
          define_method(operator) { |_| nil }

    using Refinement

    def initialize

Read more on our blog

Check out the knowledge base collected and distilled by experienced

In Ruby on Rails, view objects are an essential part of the Model-View-Controller (MVC) architecture. They play a crucial role in separating the presentation logic from the business logic of your a...


Recently I got assigned to an old project and while luckily it had instructions on how to set it up locally in the the number of steps was damn too high. So instead of wasting half a da...


Did you ever use Vim, top or its better alternative, htop? Immortal Midnight Commander? Or maybe the more user friendly version of du, ncdu? They are all terminal applications working in full scree...

Powstańców Warszawy 5
15-129 Białystok

+48 668 842 999