Skip to content

Instantly share code, notes, and snippets.

@stephanschubert
Created February 5, 2010 18:39
Show Gist options
  • Save stephanschubert/296073 to your computer and use it in GitHub Desktop.
Save stephanschubert/296073 to your computer and use it in GitHub Desktop.
Recursive fibonacci with memoization
def memoize(name)
cache = {}
(class << self; self; end).send(:define_method, name) do |*args|
cache[args] = super(*args) unless cache.has_key?(args)
cache[args]
end
end
def fib(n)
return n if n < 2
fib(n-1) + fib(n-2)
end
memoize(:fib)
fib(100) # => 354224848179261915075
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment