Memoizing in Ruby

Memoization is the pattern of calculating a value once, and re-using that value each subsequent time it is needed. It’s common to encounter this in Ruby in the form @variable ||= calculation. It’s so common that it is often used even where it’s not expensive or re-used; it’s become a part of idiomatic Ruby. In my last post I made an off-hand reference to solving the problem of using memoization for falsy values, and it seems a topic worth talking about in and of itself.

Read more…

The Local Variable Aversion Antipattern

In my experience writing Ruby, a strong aversion to using local variables is something I have noticed again and again. I would propose that in most scenarios this has several underrecognized drawbacks. The solution is easy: use local variables.

Read more…

Instrumenting Ruby Methods

Instrumentation is the addition of measurement to code - for example timing how long Ruby is spending in a given method. There are many approaches to adding instrumentation to code in Ruby - whether it’s using 3rd party services like New Relic and Datadog, using libraries like Rubyprof, or even plain old logging. Here I propose an unintrusive Ruby 2.0+ technique to add instrumentation to arbitrary methods. If you want to jump straight to the proposed code without the explanation of how or why we got there, here’s your TLDR.

Read more…