| Path: | README |
| Last Update: | Sat Dec 31 22:06:54 Mountain Standard Time 2005 |
A method that speeds methods up at the cost of memory (or disk space).
Ruby 1.8.0 or later
ruby test/tc_memoize.rb (optional) ruby install.rb
ruby test/tc_memoize.rb (optional) ruby memoize.gemspec gem install memoize-x.y.z.gem # Where 'x.y.z' is the version
require "memoize"
include Memoize
# Inefficient fibonacci method
def fib(n)
return n if n < 2
fib(n-1) + fib(n-2)
end
fib(100) # Slow
memoize(:fib)
fib(100) # Fast
# Or store the cache to a file for later use
memoize(:fib, "fib.cache")
fib(100) # Fast
Memoize::MEMOIZE_VERSION
Returns the version of this package as a String.
Memoize#memoize(method, file=nil)
Takes a +method+ (symbol) and caches the results of +method+ in a hash table. If you call +method+ again with the same arguments, memoize gives you the value from the table instead of letting the method compute the value again. If +file+ is provided, the results are cached to that file instead of in memory. Note that this uses Marshal internally, so don't expect your cache to work between different versions of Ruby, should you happen to upgrade. Returns the cache, which you can inspect or manipulate directly if you are so inclined.
Code borrowed from Nobu Nakada (ruby-talk:155159). Code borrowed from Ara Howard (ruby-talk:173428). Ideas taken from Brian Buckley and Sean O'Halpin.
Ruby's
(C) 2005, Daniel J. Berger All Rights Reserved
Daniel J. Berger djberg96 at gmail dot com IRC nick: imperator (freenode)