lib/more/facets/memoize.rb in facets-2.4.5 vs lib/more/facets/memoize.rb in facets-2.5.0
- old
+ new
@@ -14,16 +14,17 @@
# "#{@a ^ 3 + 4}"
# end
# memoize :a
# end
#
-# t = T.new
+# t = T.new(1)
# t.a.__id__ == t.a.__id__ #=> true
#
# == Authors
#
-# * Trans
+# * trans
+# * rtb
#
# == Copying
#
# Copyright (c) 2005 Robert Feldt
#
@@ -34,10 +35,12 @@
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.
+#require 'facets/memoizer'
+
#
class Module
# Directive for making your functions faster by trading
# space for time. When you "memoize" a method/function
@@ -57,15 +60,14 @@
#
# t = T.new
# t.a.__id__ == t.a.__id__ #=> true
#
def memoize(*meths)
- @_MEMOIZE_CACHE ||= Hash.new
meths.each do |meth|
- mc = @_MEMOIZE_CACHE[meth] = Hash.new
old = instance_method(meth)
new = proc do |*args|
+ mc = ((@_MEMOIZE_CACHE ||= {})[meth] ||= {})
if mc.has_key? args
mc[args]
else
mc[args] = old.bind(self).call(*args)
end
@@ -75,26 +77,21 @@
end
end
# This allows memoize to work in main and instance scope too.
-#--
-# Would this be good to have? Will need to modify for instance level, if so.
-#++
-
def memoize(*args)
Object.memoize(*args)
end
-#
-module Kernel
+module Kernel #:nodoc:
# Object#cache is essentially like Module#memoize except
# it can also be used on singleton/eigen methods.
# OTOH, memoize's implementation is arguably better for it's
# use of #bind instead of #alias. Eventually the two implmenations
- # will be reconciled with a single implmentation.
-
+ # should be reconciled with a single implementation.
+ #
def cache m = nil
if m
(Module === self ? self : (class << self; self; end)).module_eval <<-code
alias_method '__#{ m }__', '#{ m }'
def #{ m }(*__a__,&__b__)