Last active
October 2, 2021 02:16
-
-
Save ruxo/92c1f45df28bdb755c0f to your computer and use it in GitHub Desktop.
Ruby Memoize
This file contains hidden or 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
| def memoize(method_name) | |
| cache = {} | |
| define_method(method_name) do |*args| | |
| cache[args] ||= yield(*args) | |
| end | |
| end | |
| memoize(:add) {|a,b| | |
| p "calc #{a} and #{b}" | |
| a+b | |
| } | |
| p add(23,45) | |
| p add(23,45) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment