Ruby memoization explained

Memoization is a technique you can use to speed up your accessor methods. It caches the results of methods that do time-consuming work, work that only needs to be done once. In Rails, you see memoization used so often that it even included a module that would memoize methods for you.

This is how Memoization works in Ruby

 > var1 ||= 12
 => 12 
 > var1 ||= 13
 => 12

another workaround

 > var2 = var2 || 14
 => 14 
 > var2 = var2 || 16
 => 14 

Something different

 > var2 = var3 || 16
NameError: undefined local variable or method `var3' for main:Object
 from (irb):5
 from /home/john/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
 >
 > var3 = var3 || 16
 => 16

Some real world example

You’ll see this memoization pattern all the time in Ruby:

class User < ActiveRecord::Base
  def twitter_followers
    # assuming twitter_user.followers makes a network call
    @twitter_followers ||= twitter_user.followers
  end
end

The ||= more or less translates to @twitter_followers = @twitter_followers || twitter_user.followers. That means that you’ll only make the network call the first time you call twitter_followers, and future calls will just return the value of the instance variable @twitter_followers.

 

Sources:

I would like to recommend you to read this:

http://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/

 

Leave a comment