Sha256: ad9771ed3ef797dc04ceb2ba9e393ac82ad7b537de73c3c83f26ff998ec397b1

Contents?: true

Size: 575 Bytes

Versions: 3

Compression:

Stored size: 575 Bytes

Contents

require 'facets/binding/eval'
require 'facets/kernel/__method__'

module Kernel

  # Global memo cache.
  $MEMO ||= {}

  # 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
  #
  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

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-2.9.0 lib/tour/facets/kernel/memo.rb
facets-2.9.0.pre.2 lib/tour/facets/kernel/memo.rb
facets-2.9.0.pre.1 lib/tour/facets/kernel/memo.rb