Skip to content

Instantly share code, notes, and snippets.

@michaelfairley
Created September 11, 2012 03:07
Show Gist options
  • Save michaelfairley/3695645 to your computer and use it in GitHub Desktop.
Save michaelfairley/3695645 to your computer and use it in GitHub Desktop.
def memoize(&blk)
cache = {}
lambda do |*args|
return cache[args] if cache.has_key?(args)
cache[args] = blk.call(*args)
end
end
define_singleton_method(:fib, &memoize{ |n|
if n < 2
n
else
fib(n-2) + fib(n-1)
end
})
puts fib(45)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment