Created
July 18, 2013 04:16
-
-
Save anthonylewis/6026680 to your computer and use it in GitHub Desktop.
An example of memoization using Ruby 2's module prepend.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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