Skip to content

Instantly share code, notes, and snippets.

@anthonylewis
Created July 18, 2013 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonylewis/6026680 to your computer and use it in GitHub Desktop.
Save anthonylewis/6026680 to your computer and use it in GitHub Desktop.
An example of memoization using Ruby 2's module prepend.
module Memoize
def calc(n)
@@memo ||= {}
@@memo[n] ||= super
end
end
class Fibonacci
prepend Memoize
def calc(n)
return n if n < 2
return calc(n - 1) + calc(n - 2)
end
end
puts Fibonacci.new.calc(36)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment