Method: Kernel#memo

Defined in:
lib/core/facets/kernel/memo.rb

#memo(*args, &block) ⇒ Object

Memoize a method.

class MemoExample
  attr_accessor :a
  def m
    memo{ @a }
  end
end

ex = MemoExample.new

ex.a = 10
ex.m  #=> 10

ex.a = 20
ex.m  #=> 10

NOTE: This method is not a common core extension and is not loaded automatically when using require 'facets'.

Uncommon:

  • require ‘facets/kernel/memo’



32
33
34
35
36
37
38
39
40
41
# File 'lib/core/facets/kernel/memo.rb', line 32

def memo(*args, &block)
  if args.empty?
    args = block.binding.eval('[self, __method__]')
  end
  if $MEMO.key?(args)
    $MEMO[args]
  else
    $MEMO[args] = block.call
  end
end