All posts

How to memoize a conditional in Ruby

In Ruby memoization is a performance optimization. It allows you to execute some code, save it in a variable and not have execute that code again if the method is invoked, instead just return the value of a variable.

In the below code some_method will only execute the Account.find call the first time the method is invoked in on the object.

class MyClass
  def some_method
    @account ||= Account.find(3)  
  end
end

I learned recently that you can memoize the return value of a conditional expression as well. To do this wrap the expression in a begin block and if some_method is invoked more than once the condition will not be run after the first invocation. During the first invocation the conditions return value was saved to @account and will be returned on each subsequent call to the method.

class MyClass
  def some_method
    @account ||= begin
      if @organization.has_accounts?
        Account.find(3)
      else
        Account.create(name: "lisa")
      end
    end      
  end
end

Similar post: How not to memoize in Ruby

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).