Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache method results in Ruby

In Python I can easily decorate methods so that they remember their result:

def store(self):
    a = line1()
    b = line2(a)
    return line3(b)

=>

from lazy import lazy

@lazy
def store(self):
    a = line1()
    b = line2(a)
    return line3(b)

Is there some similar idiom in Ruby for calculating method result only once?

like image 391
Paul Draper Avatar asked Dec 18 '22 12:12

Paul Draper


2 Answers

In Ruby this is generally called memoization and it takes the naive form of:

def store
  @store ||= begin
    a = line1
    b = line2(a)
    line3(b)
  end
end

There are important concerns if this code is used in a multi-threaded environment, though, which is why there are gems that manage this and ensure your lazy initializers are run only once if that's a concern.

like image 96
tadman Avatar answered Dec 21 '22 01:12

tadman


Another option that works with false and nil too:

def store
  unless defined?(@store) 
    a = line1
    b = line2(a)
    @store = line3(b)
  end

  @store
end
like image 37
spickermann Avatar answered Dec 21 '22 00:12

spickermann